等待每个承诺后继续循环完成

下面我有两个function。 其中一个回报是一个承诺,我希望在每一个循环等待它先完成,然后移动一个。 正如你在下面看到的结果是不是所需/同步。 我应该不使用async.forEachof

 function test(num, callback) { console.log("inside function: "+num) return new Promise((resolve, reject) => { my.promise(num).then(() => { console.log("done: "+num) resolve(callback); }).catch(e => console.error(e)); }).catch(console.error); } function start_function() { //stuff async.forEachOf(arr, function (itm, i, callback){ console.log(i) test(i, callback).catch(e => console.error(e)); }, function (err) { console.log("ALL DONE") }); } 

结果:

 0 inside function 0 1 inside function 1 2 inside function 2 done: 0 done: 2 //wrong should always be 1, finished before the previous promise. done: 1 //wrong ALL DONE 

我不想用PromiseAll不是因为我不想要,而是因为我需要每个承诺等待前一个的结果,然后开始下一个。 因此把所有这些都收集起来,然后等待它们按照任何顺序和我所需要做的来完成。

如果我没有错,你正在尝试做什么,但是你应该避免在Promise函数中传递callback并解决它。 你可以用这个代码实现同样的function,也可以从testing函数中删除callback。

 function start_function() { //stuff arr.forEach(async function (itm, i, array){ console.log(i) try { await test(i); } catch(err){ console.log(err); } }); } 

以下是testingfunction的样子,

 function test(num) { console.log("inside function: "+num) return new Promise((resolve, reject) => { my.promise(num).then(() => { console.log("done: "+num) resolve(); }).catch(e => { console.error(e) reject(e); }); }); } 

那么这个方法呢?

 (function loopOnItems(i) { dummyGoogleAPI.someAsyncMethod(data).then(function (_response) { // do something with response }) .catch(function (error) { console.error(error); }); if (--i){ loopOnItems(i); }// decrement i and call loopOnItems again if i > 0 else{ _callback(errors); } })(count); 

你有一些count ,我们调用loopOnItems方法,直到count> 0