我是 node.js 的新手,所以我想知道如何知道何时处理所有元素让我们说:
["one", "two", "three"].forEach(function(item){
processItem(item, function(result){
console.log(result);
});
});
...现在如果我想做一些只有在处理完所有项目后才能完成的事情,我该怎么做?
最佳答案
您可以使用 async module .简单的例子:
async.map(['one','two','three'], processItem, function(err, results){
// results[0] -> processItem('one');
// results[1] -> processItem('two');
// results[2] -> processItem('three');
});
async.map 的回调函数将在处理完所有项目时执行。但是,在 processItem 中你应该小心,processItem 应该是这样的:
processItem(item, callback){
// database call or something:
db.call(myquery, function(){
callback(); // Call when async event is complete!
});
}
关于node.js - 如何知道何时完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10776891/