赶上回调​​异步函数完成的那一刻

时间:2019-03-19 16:38:16

标签: javascript html html5 asynchronous

我有以下代码来呈现要上传的选择文件:

  //1
  <input type="file" multiple id="my_html_uploader" />


//2
var files = myHtmlUploaderElem.files;
if (files.length > 0) {
  for (var i = 0, file1; file1 = files[i]; i++) {
    var reader = new FileReader();
    reader.onload = (function(file2, i2) {
      return function(e) {
        alert("done!");
      };
    })(file1, i);

    reader.readAsDataURL(f);
  }
}

如何捕获 reader.onload(...)的回调

a)一个单独的文件

b)所有已选择的文件

1 个答案:

答案 0 :(得分:0)

创建承诺,然后您就可以使用Promise.all等待它们了:

const promises = []; // keep as much constant as possible

for (const file of files) { // way more beautiful, no need for an IIFE with "const" or "let"
  let reader = new FileReader();

  promises.push(new Promise((resolve, reject) => { // short for: function(resolve, reject) {
    reader.onload = event => resolve(event.target.result);
    reader.onerror = reject;
  }));

  reader.readAsDataURL(file);
}

Promise.all(promises).then(results => {
  alert("all loaded");
  // results is an array of file contents
}).catch(error => {
  // one of the files failed to load, handle that here
});