gpt4 book ai didi

javascript Promise.all 只返回最后一个 promise

转载 作者:数据小太阳 更新时间:2023-10-29 05:11:54 27 4
gpt4 key购买 nike

我有一个这样的脚本:

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 循环 中,它只给我最后一个索引和最后一个索引的值,而我想要每个循环的值并使用键和值执行一些操作。但我得到的是最后一个只有键和值..

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

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

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

无论如何,我可以在每个循环中获取 promise 的索引吗?

最佳答案

for 循环中 .then() 处理程序中的 i 变量不是您认为的那样。在调用任何 .then() 处理程序之前,您的 for 循环已经运行完成(因为它们总是在未来的滴答中异步运行)。因此,你只是认为你看到了最后一个 promise ,但实际上所有的 promise 都工作正常,只是它们都返回了 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))

关于javascript Promise.all 只返回最后一个 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38605878/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com