【问题标题】:Add promise result to items in array将承诺结果添加到数组中的项目
【发布时间】:2015-03-26 15:53:18
【问题描述】:

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

文件是一个FileList 对象。

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

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

【问题讨论】:

  • 这是循环和闭包的问题,​​之前已在此处回答过,例如,请参阅 stackoverflow.com/q/750486/623518stackoverflow.com/q/27254735/623518
  • 你真的应该使用Promise.all 而不是手动分配甚至覆盖任何地方的东西。顺便说一句,data[last] 是具有filesrc 属性的对象文字,并且没有then 方法?
  • 你是对的,我在提取代码示例时错过了 src。我会看看 .all,我对 Promise 还是很陌生。

标签: javascript asynchronous filereader


【解决方案1】:

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

可以通过将索引绑定到回调来解决:

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

【讨论】:

  • 谢谢,这已经成功了,但你能告诉我索引是从哪里来的吗,为什么你将 null 传递给绑定?
  • .bind 返回一个新函数并将第二个和更多参数传递给该函数。所以index 传递了last 的值。 .bind 的第一个参数是 this 绑定的值。但是由于我们不需要将this 绑定到特定值,所以我只是传递了null。在此处了解有关.bind 的更多信息:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
猜你喜欢
  • 1970-01-01
  • 2020-07-02
  • 2016-09-14
  • 2016-04-04
  • 2016-11-12
  • 2017-12-27
  • 2016-09-17
  • 2016-07-30
  • 1970-01-01
相关资源
最近更新 更多