javascript Promise.all仅返回最后一个承诺

gam*_*mer 6 javascript promise es6-promise

我有一个脚本,如:

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))
Run Code Online (Sandbox Code Playgroud)

这里在我的for loop它只给了我最后一个索引和最后一个索引的值,而我想要每个循环的值,并执行一些关键和值的动作..但我只得到最后一个键和值..

我试图获得价值Promise.all的回应,但没有奏效.

如何在allPromises响应中获取数组的索引?

我可以通过制作一个柜台来做到这一点.但是当我再次调用该函数时,计数器被重置,所以我不想使用计数器.

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

jfr*_*d00 8

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))
Run Code Online (Sandbox Code Playgroud)

或者,因为您正在生成数组,所以您可以使用.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))
Run Code Online (Sandbox Code Playgroud)