如何在没有库(如 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
});
}
谢谢
更新 (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();
}
}
});
}
最佳答案
您可以使用 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);
});
不过,如果您实际上不需要捕获这些 promise 解决方案的结果,那么这可能超出您的需要。另请注意,您在它的末尾仍然会有一个 promise ,其中将包含每个 promise 的结果数组,对应于它们的原始数组位置。
此外,这里是 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);
});
}
关于javascript - 在没有 JS 库的情况下使 for 循环等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36901476/