怎么知道什么时候完成

时间:2012-05-27 20:10:50

标签: node.js asynchronous

我是node.js的新手,所以我想知道如何知道所有元素的处理时间让我们说:

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

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

3 个答案:

答案 0 :(得分:5)

您可以使用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!
   });
}

答案 1 :(得分:1)

forEach正在阻止,请参阅此帖:

JavaScript, Node.js: is Array.forEach asynchronous?

所以要在所有项目完成处理后调用函数,可以内联完成:

["one", "two", "three"].forEach(function(item){
    processItem(item, function(result){
        console.log(result);
    });
});
console.log('finished');

如果要处理的每个项目都有高的io-bound负载,那么请看看Mustafa推荐的模块。在上面链接的帖子中也引用了一种模式。

答案 2 :(得分:1)

虽然其他答案都是正确的,因为node.js今后支持ES6,在我看来,使用内置的Promise库会更加稳定和整洁。

您甚至不需要任何东西,Ecma使用 Promises / A + 库并将其实现为原生Javascript。

Promise.all(["one", "two","three"].map(processItem))
  .then(function (results) {
    //  here we got the results in the same order of array
} .catch(function (err) {
    //  do something with error if your function throws
}

由于Javascript在调试时是一个充分问题的语言(动态类型,异步流),坚持使用promise而不是回调将节省你的时间。

相关问题