Been struggling with this, so thought I would see if anyone have a quick answer. Been trying to get async to work doing parallel calls, and have managed to do that (thanks to others :) ).
However, I now have the problem that I need to send a variable into the callback function. Basically, I am trying to use mongoose to make five requests to the database to find level 0-5 in a table.
Set up a for loop that iterates from 0 to 4, each loop makes a queries.push. Once that loop is done, it calls async.parallel to wait for replies. All that works, except reading i, which contains the number between 0-4. At first I thought I could just send it in by adding (i) in the closure. But that brakes the call to async.parallel (think it finds it and identifies it as not being a function). Think bind is the answer, but not certain to what I should bind to.
console.log("Lets see if we can't figure out this one once and for all");
var queries= [];
var maxLevels = 1;
for ( var i = 0; i < maxLevels; i++ ){
console.log("Looking for "+ i)
queries.push(function (cb) {
console.log("Seaching for "+ i)
Skill.find({level: i}).exec(function (err, docs) {
if (err) {
throw cb(err);
}
// do some stuff with docs & pass or directly pass it
cb(null, docs);
});
});
}
console.log("In theory we now have 5 requests");
async.parallel(queries, function(err, docs) {
// if any query fails
if (err) {
throw err;
}
console.log("This is what we got back")
for (var doc in docs){
console.log("Lets find 0")
cuDoc = docs
if (cuDoc === undefined ){
console.log("Got nothing on "+ cuDoc);
} else {
console.log("Looking at " + cuDoc);
}
}
})