微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐