繁体   English   中英

Node.js async.each等待第一个循环

[英]Nodejs async.each wait for first loop

我正在尝试异步处理rowsArr(说100条记录),但是我只想一次从数据库加载国家列表以避免数据库连接。 我正在尝试下面的示例代码,但它打开数据库连接100次。

var countryList = null;

async.each(rowsArr, function(row, callback) {


    if( countryList == null )
    {
        console.log("open database here to get country list and then assign to below variable");

        countryList = countriesFromDatabase;

        callback( countryList );
    }
    else
    {
        callback( countryList );
    }


}, function(err){

      console.log("all rows are processed");

});

它与async.eachSeries正常工作,但我希望以异步方式进行操作。 有什么建议吗?

  1. 从数据库获取国家
  2. 处理所有行

所以下面的工作

function getCountries(callback) {
  console.log("open database here to get country list and then assign to below variable");
  callback(null,countriesFromDatabase);
}
getCountries(function(err, countriesFromDatabase) {
 // use countries in following async loop
  async.each(rowsArr, function(row, callback) {
    callback(null, row); //process row here
  }, function(err) {
    console.log("all rows are processed");
  });
});

它实际上执行了应做的工作,所有数百行处理同时开始,并且它们正在传递if块。

您可能要使用锁。 https://github.com/BorisKozo/node-async-locks

这样,您可以锁定countryList检查过程以避免多个数据库连接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM