简体   繁体   English

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

[英]Nodejs async.each wait for first loop

I am trying to process rowsArr (lets say 100 records) asynchronous but I want to load country list from database only one time to avoid database connections. 我正在尝试异步处理rowsArr(说100条记录),但是我只想一次从数据库加载国家列表以避免数据库连接。 I am trying below example code but it is opening database connections 100 times. 我正在尝试下面的示例代码,但它打开数据库连接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");

});

It is working fine with async.eachSeries but I want it in asynchronous manner. 它与async.eachSeries正常工作,但我希望以异步方式进行操作。 Any suggestion? 有什么建议吗?

  1. Get Countries from database 从数据库获取国家
  2. Process all rows 处理所有行

So following will work 所以下面的工作

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");
  });
});

It does what it should actually, all hundred rows processing starts at the same time and they're passing the if block. 它实际上执行了应做的工作,所有数百行处理同时开始,并且它们正在传递if块。

You might want to use locks. 您可能要使用锁。 https://github.com/BorisKozo/node-async-locks https://github.com/BorisKozo/node-async-locks

That way you can lock your countryList checking process to avoid multiple database connections. 这样,您可以锁定countryList检查过程以避免多个数据库连接。

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

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