Reputation: 2970
I want to know how to handle dependencies in using the async library in Node.js, look at the following example:
db.open(function(error, client) {
client.collection(('my-collection', function(error, collection) {
collection.insert({ "email": "[email protected]" }, function(error, docs) {
// Do stuff.
});
});
});
Using the async library:
async.parallel([
function(callback) {
db.open(function(error, client) {
callback(error, client);
});
},
function(callback) {
// How do I access the "client" variable at this point?
}
],
function(results){
// Do stuff.
});
Upvotes: 1
Views: 2046
Reputation: 688
You are using async parallell, which runs all functions together and they can finish in any order.
you can use the async waterfall function which passes varibles from one callback to the next function eg.
async.waterfall([
function(callback){
callback(null, 'one', 'two');
},
function(arg1, arg2, callback){
callback(null, 'three');
},
function(arg1, callback){
// arg1 now equals 'three'
callback(null, 'done');
}
], function (err, result) {
// result now equals 'done'
});
or you can use the auto function, which allowes you to specify which other functions must finish first eg.
async.auto({
get_data: function(callback){
// async code to get some data
},
make_folder: function(callback){
// async code to create a directory to store a file in
// this is run at the same time as getting the data
},
write_file: ['get_data', 'make_folder', function(callback){
// once there is some data and the directory exists,
// write the data to a file in the directory
callback(null, filename);
}],
email_link: ['write_file', function(callback, results){
// once the file is written let's email a link to it...
// results.write_file contains the filename returned by write_file.
}]
});
so what you could do in your case is this:
async.auto({
dbReady: function(callback) {
db.open(function(error, client) {
callback(error, client);
});
},
connected: ['dbReady', function(callback, results){
// How do I access the "client" variable at this point?
console.log(results.dbReady);
}
},
function(results){
// Do stuff.
});
Have a look at this to see all the available functions and their uses
Upvotes: 4