node.js - 如何知道何时完成

标签 node.js asynchronous

我是 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/

相关文章:

android - 使用 nodejs 相应地重定向到 PlayStore 或 AppStore 的公共(public)链接

javascript - pm2 在集群模式下弃用了 worker

c# - 异步上传和调整多个图像时出现内存不足异常

javascript - 通过 Passport 实例的快速路由中的路由分离

node.js - Selenium-Webdriver 错误

javascript - 这个javascript语法是什么意思 : const { headers, method, url } = request;

html - 在网页上以非阻塞方式调用URL

c++ - ASIO 直接从异步解析中获取 tcp 端点

node.js - 意外行为 - IIFE 需要时异步等待?

javascript - promise 错误/异常处理设计