I’m trying to get the duration in seconds of every object in a list but I’m having some trouble in my results. I think it’s because I’m not fully understanding asynchronous behavior.
I start my function with an array songs[]
of n
number of objects. By the end of my function, the goal is to have an array songLengths
where the first value is the duration of the first object in songs[]
, and so on.
I’m trying to model my function after this example: JavaScript closure inside loops – simple practical example. But I’m getting undefined values for each songLengths[]
index.
$("#file").change(function(e) {
var songs = e.currentTarget.files;
var length = songs.length;
var songLengths = [];
function createfunc(i) {
return function() {
console.log("my val = " + i);
};
}
for (var i = 0; i < length; i++) {
var seconds = 0;
var filename = songs[i].name;
var objectURL = URL.createObjectURL(songs[i]);
var mySound = new Audio([objectURL]);
mySound.addEventListener(
"canplaythrough",
function(index) {
seconds = index.currentTarget.duration;
},
false,
);
songLengths[i] = createfunc(i);
}
});
Something like this should work without a mess of closures, and with added clean asynchronicity thanks to promises.
Basically we declare a helper function,
computeLength
, which takes a HTML5File
and does the magic you already did to compute its length. (Though I did add theURL.revokeObjectURL
call to avoid memory leaks.)Instead of just returning the duration though, the promise resolves with an object containing the original file object and the duration calculated.
Then in the event handler we map over the
files
selected to createcomputeLength
promises out of them, and usePromise.all
to wait for all of them, then log the resulting array of[{file, duration}, {file, duration}, ...]
.