将承诺结果添加到数组中的项目

Add promise result to items in array

我一直在尝试将文件及其匹配的数据 url 添加到数组中的对象中。

文件是一个 FileList 对象。

我首先在 Filereaderonloadend 事件中尝试了此操作,但在读取过程中无法访问原始文件,因此转向了 promises。

var data = [];
for(var i = 0; i < files.length; i++){
   data.push({
        file: files[i],   //keep the files for uploading
        src: readFile(files[i]) // generate the src to offer preview image
    });
    var last = data.length -1;
    console.log(last); //log a
    data[last].src.then(function(result){
        console.log(last); // log b
        data[last].src = result // overwrite the src deffered object with the result of the promise
    });
}

readFile 正在返回一个延期承诺,假设这是有效的。

这在文件长度为 1 时工作正常,但当文件长度为多个时我遇到了异步方面的问题并且它仅适用于最后一项。

基于 2 个文件 (files.length == 2) 的日志结果:

0 //log a
1 //log a
1 //log b <-- ignores 0 stays as 1
1 //log b

期待 0101

这是一个常见问题:JavaScript closure inside loops – simple practical example

可以通过回调绑定index来解决:

data[last].then(function(index, result){
    data[index].src = result;
}.bind(null, last));