I'm working in Node.js (Express) and MongoDB (mongooseJS). I want to create async functions (one after another, quering DB in proper order);
the question is: how can I create variable number of async.series functions, like this:
var supply = [0];
async.series([
function(callback) {
Model.find({ color: user.color[supply] }).exec(callback);
},
],function(err, results){
res.send('Chosen colors: ' + results);
});
and if - lets say - variable supply = [0, 1, 2],
then callback function will be tripled with 0, 1 and 2 placed there:
var supply = [0, 1, 2];
async.series([
function(callback) {
Model.find({ color: user.color[supply] }).exec(callback); // supply = 0
},
function(callback) {
Model.find({ color: user.color[supply] }).exec(callback); // supply = 1
},
function(callback) {
Model.find({ color: user.color[supply] }).exec(callback); // supply = 2
},
],function(err, results){
res.send('Chosen colors: ' + results);
});
in other words, how can i loop this fragment
function(callback) {
Model.find({ color: user.color[supply] }).exec(callback);
},
so number of functions will be here depending on some variable?
Cheers!
Mike
You could just use async.mapSeries() since it is designed to iterate over an array. Example:
var supply = [0];
async.mapSeries(supply, function(val, callback) {
Model.find({ color: user.color[val] }).exec(callback);
}, function(err, results) {
if (err) throw err;
// all done!
console.dir(results);
});
This assumes that .exec() calls the callback such that the error is first and the value is second.