怎么知道什么时候完成

Bad*_*ees 6 asynchronous node.js

我对node.js很新,所以我想知道如何知道何时处理所有元素让我们说:

["one", "two", "three"].forEach(function(item){
    processItem(item, function(result){
        console.log(result);
    });
});
Run Code Online (Sandbox Code Playgroud)

...现在,如果我想做一些只能在处理完所有项目时才能完成的事情,我该怎么做?

Mus*_*afa 5

您可以使用异步模块.简单的例子:

async.map(['one','two','three'], processItem, function(err, results){
    // results[0] -> processItem('one');
    // results[1] -> processItem('two');
    // results[2] -> processItem('three');
});
Run Code Online (Sandbox Code Playgroud)

处理所有项目时,async.map的回调函数.但是,在processItem中你应该小心,processItem应该是这样的:

processItem(item, callback){
   // database call or something:
   db.call(myquery, function(){
       callback(); // Call when async event is complete!
   });
}
Run Code Online (Sandbox Code Playgroud)