Reputation: 1606
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. I am trying below example code but it is opening database connections 100 times.
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. Any suggestion?
Upvotes: 2
Views: 656
Reputation: 589
It does what it should actually, all hundred rows processing starts at the same time and they're passing the if block.
You might want to use locks. https://github.com/BorisKozo/node-async-locks
That way you can lock your countryList checking process to avoid multiple database connections.
Upvotes: 0
Reputation: 7742
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");
});
});
Upvotes: 3