如何在没有库(如jQuery)的情况下开始循环的新迭代之前创建一个等待异步调用完成的for
循环?
示例:
var items = [1,2,3,4,5];
for (var i = 0; i < items.length; i++) {
var promise = new Promise(function(resolve, reject){
asyncAPIcall({
body : item[i]
}, function(error, response){
if(error) {
reject();
} else {
resolve();
}
});
promise.then(function() {
//continue loop
}, function() {
//break loop
});
}
&#13;
由于
更新(4/29)
我想到了这个解决方案,我创建了一个自我调用的函数:
var items = [1,2,3,4,5];
var counter = items.length - 1; //minus one since array is zero based.
function myLoop(){
asyncAPIcall({
body : item[counter]
}, function(error, response){
if(error) {
// Error message.
} else {
counter = counter - 1;
if(counter == -1){
//Done
}
else {
myLoop();
}
}
});
}
&#13;
答案 0 :(得分:3)
您可以使用reduce来使它们按顺序处理(或使用常规for循环设置promise链 - 我更喜欢reduce,我自己)。
let promise = items.reduce((carry, current) => {
return carry.then(arr => {
return asyncAPIcall({ body: current }).then(result => arr.concat([ result ]));
});
}, Promise.resolve([]));
promise.then(finalResult => {
console.log('final result:', finalResult);
});
如果您实际上不需要捕获这些承诺解决方案的结果,这可能比您需要的更多。另请注意,您最后仍会有一个承诺,它将包含每个承诺的结果数组,与其原始数组位置相对应。
此外,这里是asyncAPIcall
的模拟版本,如果你想跟踪调用方法的方式/位置,它应该有助于显示这里的操作顺序。
function asyncAPIcall(obj) {
console.log('asyncAPIcall for:', obj);
return new Promise((resolve) => {
setTimeout(() => {
let resolution = obj.body + 5; // change the value in some way, just to show that input !== output
console.log('resolving with:', resolution);
return resolve(resolution);
}, 100);
});
}