【发布时间】:2017-09-21 19:02:00
【问题描述】:
我有一个 foreach 循环,我在其中调用一个异步函数。如何确保所有异步函数都调用了指定的回调函数,然后运行一些东西?
【问题讨论】:
标签: javascript node.js asynchronous
我有一个 foreach 循环,我在其中调用一个异步函数。如何确保所有异步函数都调用了指定的回调函数,然后运行一些东西?
【问题讨论】:
标签: javascript node.js asynchronous
保留一个柜台。 示例:
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();
}
});
});
正如另一个答案所说,您可以使用非常好的 async 包。但为了它,我建议使用 Promises 并使用 Vanila Promise.all()。示例:
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
});
【讨论】:
您可以为此使用Async 库。它具有各种有用的实用功能。
其中有一个 Queue 函数,可用于执行一组任务,当所有任务执行完毕时,您会收到一个回调,您可以在其中做任何您想做的事情。您还可以控制队列的并发性(一次并行执行多少个任务)。
这是一个示例代码-
// 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');
});
【讨论】: