javascript Promise.all仅返回最后的承诺

游戏玩家

我有一个像这样的脚本:

var a = [{'a': 1},{'b': 2}]
var allPromises = new Array(a.length)
for(var i in a) {
    allPromises[i] = Promise.resolve().then(response => {
      console.log(i)
      console.log(a[i])
      // Do somethig on every loop with key and value
      return i
    })
}

Promise.all(allPromises).then(response => console.log(response))

在我这里,for loop它只给我最后一个索引和最后一个索引的值,而我想要每个循环上的值并使用键和值执行一些操作。。但是我只得到最后一个键和值。

我尝试获取Promise.all的响应的价值,但没有成功。

我如何获得数组的索引对allPromises响应?

我可以做一个柜台。但是,当我再次调用该函数时,计数器将重置,因此我不想使用该计数器。

无论如何,我可以在每个循环上获取索引以取得承诺吗?

jfriend00

i循环.then()处理程序中的变量for不是您想的那样。您的for循环已经运行至完成任何你的前.then()处理程序被调用(因为他们总是在将来的壁虱异步运行)。因此,您仅以为自己看到的是最后一个承诺,但实际上所有的承诺都可以正常工作,只是它们都返回的最后一个值i

您可以使用.forEach()迭代数组来修复它,因为它唯一地捕获的每个值i

var a = [{'a': 1},{'b': 2}]
var allPromises = new Array(a.length);
a.forEach(function(item, i) {
     allPromises[i] = Promise.resolve().then(response => {
      console.log(i)
      console.log(a[i])
      // Do somethig on every loop with key and value
      return i
    })
});

Promise.all(allPromises).then(response => console.log(response))

或者,由于要生成数组,因此可以使用.map()

var a = [{'a': 1},{'b': 2}]
var allPromises = a.map(function(item, i) {
  return Promise.resolve().then(response => {
    console.log(i)
    console.log(a[i])
    // Do somethig on every loop with key and value
    return i
  })
});

Promise.all(allPromises).then(response => console.log(response))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章