gpt4 book ai didi

javascript - 如何使用以任意顺序返回的 promise 存储 for 循环的计数?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:05:05 24 4
gpt4 key购买 nike

我正在发出一系列 http 请求,我需要在它们返回时将结果归档到列表对象中。我正在使用 Angular promise 。

因为 promises 只在 for 循环完成后才 resolve,所以它们都被归档到列表的最后一个索引中。

for (var i = 0;i < list.length; i+=1) {
Promise.do(action).then(function(result) {
list[i] //i is always at last index because the for loop has already completed
}
}

最佳答案

Bind索引作为接收结果的函数的参数:

for (var i = 0;i < list.length; i+=1) {
Promise.do(action).then((function(index, result) {
list[index]
}).bind(null, i));
}

关于javascript - 如何使用以任意顺序返回的 promise 存储 for 循环的计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25325037/

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