我正在发出一系列 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/