在不使用JS库的情况下进行for循环等待 [英] Making a for loop wait WITHOUT a library in JS
问题描述
如何创建一个for
循环,以等待异步调用完成,然后再开始新的循环迭代而无需库(如jQuery)?
How can one create a for
loop that waits for an asynchronous call to complete prior to starting a new iteration of a loop WITHOUT a library (like jQuery)?
示例:
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)
我想到了这个解决方案,在其中创建了一个调用自身的函数:
I thought of this solution, where I create a function that calls itself:
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,我自己).
You can use reduce to make them process sequentially (or set up the promise chain using a regular for loop -- I prefer reduce, myself).
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的结果数组,对应于它们的原始数组位置.
This may be more than you need, if you don't actually need to capture the results of those promise resolutions, though. Also note that you'll still have a promise at the end of it, which will contain an array of the results of each promise, corresponding to their original array position.
此外,这是asyncAPIcall
的模拟版本,如果您想跟踪方法的调用方式/位置,它应该有助于在此处显示操作顺序.
Also, here is a mocked version of the asyncAPIcall
, which should assist with showing the order of operations here, if you want to trace through how / where the methods are called.
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);
});
}
这篇关于在不使用JS库的情况下进行for循环等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!