类似这样的东西应该可以在没有大量闭包的情况下工作,并且由于
promises
.
基本上我们声明了一个helper函数,
computeLength
File
你已经用魔法计算了它的长度。(尽管我添加了
URL.revokeObjectURL
调用以避免内存泄漏。)
但是,promise不只是返回持续时间,而是使用包含原始文件对象和计算的持续时间的对象来解析。
files
选择创建
计算长度
他们的承诺,以及
Promise.all
[{file, duration}, {file, duration}, ...]
.
function computeLength(file) {
return new Promise((resolve) => {
var objectURL = URL.createObjectURL(file);
var mySound = new Audio([objectURL]);
mySound.addEventListener(
"canplaythrough",
() => {
URL.revokeObjectURL(objectURL);
resolve({
file,
duration: mySound.duration
});
},
false,
);
});
}
$("#file").change(function(e) {
var files = Array.from(e.currentTarget.files);
Promise.all(files.map(computeLength)).then((songs) => {
console.log(songs);
});
});