[英]How to make sure that a foreach loop running async calls finished?
I have a foreach loop, where I call an async function. 我有一个foreach循环,在这里我调用了异步函数。 How can I make sure that all the async functions called the specified callback function, and after that, run something? 如何确保所有异步函数都调用了指定的回调函数,然后再运行某些东西?
Keep a counter. 保持柜台。 Example: 例:
const table = [1, 2, 3];
const counter = 0;
const done = () => {
console.log('foreach is done');
}
table.forEach((el) => {
doSomeAsync((err, result) => {
counter++;
if (counter === 3) {
done();
}
});
});
As the other answer says, you can use the async package which is really good. 就像另一个答案所说的,您可以使用异步包,这真的很好。 But for the sake of it I recommend using Promises and use the Vanila Promise.all(). 但是出于这个原因,我建议使用Promises并使用Vanila Promise.all()。 Example: 例:
const table = [1, 2, 3];
Promise.all(table.map((el) => {
return new Promise((resolve, reject) => {
doSomeAsync((err, result) => {
return err ? reject(err) : resolve(result);
});
});
}))
.then((result) => {
// when all calls are resolved
})
.catch((error) => {
// if one call encounters an error
});
You can use Async library for this. 您可以为此使用异步库。 It has various useful utility functions. 它具有各种有用的实用程序功能。
There is a Queue function in it which can be used to execute a set of tasks and you get a callback when all tasks are executed where you can do whatever you want. 其中有一个Queue函数,该函数可用于执行一组任务,并且在执行所有任务时,您会得到一个回调,您可以在其中做任何想做的事情。 You can also control the concurrency of your queue(how many tasks are executed at a time in parallel). 您还可以控制队列的并发性(一次并行执行多少个任务)。
Here is a sample code- 这是一个示例代码-
// create a queue object with concurrency 2
var q = async.queue(function(task, callback) {
console.log('hello ' + task.name);
callback();
}, 2);
// The callback function which is called after all tasks are processed
q.drain = function() {
console.log('all tasks have been processed');
};
// add some tasks to the queue
q.push({name: 'foo'}, function(err) {
console.log('finished processing foo');
});
q.push({name: 'bar'}, function (err) {
console.log('finished processing bar');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.