javascript – 如何使用以任意顺序返回的promise来存储for循环的计数?
作者:互联网
我正在制作一系列http请求,我需要在返回时将结果存档到列表对象中.我正在使用有角度的承诺.
因为promise只在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
}
}
解决方法:
我会尝试使用$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);
});
从文档:
Returns a single promise that will be resolved with an array/hash of
values, each value corresponding to the promise at the same index/key
in the promises array/hash. If any of the promises is resolved with a
rejection, this resulting promise will be rejected with the same
rejection value.
标签:angular-promise,javascript,angularjs,promise 来源: https://codeday.me/bug/20190830/1769045.html