我一直在尝试做的是将文件及其匹配的 dataurl 添加到数组中的对象中。
文件是 FileList目的。
我首先在 Filereader 的 onloadend
事件中尝试了这个但在阅读过程中无法访问原始文件,因此转到 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
正在返回一个延迟 promise ,假设这是有效的。
这在文件长度为 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 .
可以通过将索引绑定(bind)到回调来解决:
data[last].then(function(index, result){
data[index].src = result;
}.bind(null, last));
关于javascript - 将 promise 结果添加到数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28180547/