在JS中做一个for循环等待一个库

如何创build一个for循环等待一个asynchronous调用完成之前开始一个循环的新的迭代没有库(如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)

我想到了这个解决scheme,我创build了一个自称的函数:

 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链 – 我宁愿减less自己)。

 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); }); 

但是,如果您实际上不需要捕获这些承诺解决scheme的结果,则这可能比您需要的要多。 还要注意,在它的最后还会有一个承诺,它将包含每个承诺的结果数组,对应于它们的原始数组位置。

另外,这里是asyncAPIcall的一个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); }); }