I have just started with NodeJs and dealing with asynchronous functions. I tried to do multiple MongoDB calls from a for loop, and I need to wait for all of them to complete before the next step.
I have tried to implement it using async, but it seems like all my variable outside the calls are not accessible. Any idea how to make it work?
var sample = req.body; // sample will be an array list of items
var stringList = "";
var calls = [];
for(var i = 0; i < sample.length; i++) {
console.log(sample[].item) // i can print it here
calls.push(function(callback) {
db3.table.find({column1:sample[i].item}, function(err, temp){ // i hit an error here, it cannot find sample[i].item...
if (err)
return callback(err);
stringList = stringList + temp[0].item2;
callback(null, stringList );
});
});
}
async.parallel(calls, function(err, result) {
if (err)
return console.log(err);
console.log(result); // I am expecting a string of all the item2 returned and concatenated previously
});