我正在发出一系列http请求,当结果返回时,我需要将结果归档到list对象中。我用的是棱角分明的承诺。
因为承诺只有在for循环完成后才会解析,所以它们都会被归档到列表的最后一个索引中。
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
}
}发布于 2014-08-15 10:46:35
为此,我将尝试使用$q.all:
var promises = [];
for (var i = 0; i < list.length; i += 1) {
promises.push(Promise.do(action));
}
$q.all(promises).then(function(results) {
console.log(results);
});从文件中:
返回将使用值的数组/散列解析的单个承诺,每个值对应于承诺数组/散列中相同索引/键下的承诺值。如果任何承诺都是通过拒绝来解决的,则此结果承诺将以相同的拒绝值被拒绝。
发布于 2014-08-15 11:47:08
绑定索引作为接收结果的函数的参数:
for (var i = 0;i < list.length; i+=1) {
Promise.do(action).then((function(index, result) {
list[index]
}).bind(null, i));
}发布于 2014-08-15 10:45:16
不要使用标准循环。使用Array.forEach代替。每次调用提供给forEach的函数时,您都会得到一个新的闭包,从而得到一个i的新副本
https://stackoverflow.com/questions/25325037
复制相似问题