我正在使用promises
来处理任务列表:
这是代码示例:
var array = ["aaa", "bbbb", "cccc", "dddd", "eeee"];
var result = [];
var p = Promise.resolve({
then: function(onFulfill, onReject) {
array.forEach(function(x){
// http request with x and make sure this request ends before a new one if fired
// put http resolte in array : result.push(httpRespose);
});
//when done, onFulfill(result)
}
});
p.then(
function(v) {
console.log(v); // "fulfilled!"
}, function(e) {
console.log(e); // not called
});
我希望能够使用数组中的每个元素发出 http 请求,然后将结果放入另一个数组中,完成后返回该新数组。我还想知道是否可以确保http结果以相同的顺序添加(这不是很重要)。
有人可以帮忙吗?
最佳答案
Promise.all
用于等待多个 Promise 履行。
每次创建 Promise 时,将其推送到数组中,然后使用
Promise.all(myPromiseArray).then(allDoneHandler)
这是一个例子:
var items = [ 500, 1000, 1500 ];
var results = [];
items.forEach((item) => {
let promise = new Promise((resolve) => {
setTimeout(() => {
console.log(item);
resolve(item);
}, item);
});
results.push(promise);
});
Promise.all(results).then(() => {
console.log('done!');
});
关于Javascript - 如何使用循环正确处理 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40752153/