Waiting for multiple callbacks in Node.js
You could also do it using when and promises, which IMHO is the easiest to read.
var promises = [];if(x) { var deferred1 = when.defer(); doSomethingAsync({ callback: deferred1.resolve }); promises.push(deferred1.promise);} else if(y) { var deferred2 = when.defer(); doSomethingAsync({ callback: deferred2.resolve }); promises.push(deferred2.promise);} else if(z) { var deferred3 = when.defer(); doSomethingAsync({ callback: deferred3.resolve }); promises.push(deferred3.promise);}when.all(promises).then(function () { console.log('Finished Promises');});
Here's one way with async series.
https://github.com/caolan/async#series
async.series([ function(callback){ if(foo === bar){ function1(arg1, function(val1){ callback(null, val1); }); }else if(foo === baz){ function2(arg2, function(val2){ callback(null, val2); }); }else{ function3(arg3, function(val3){ callback(null, val3); }); } } ], function(error, valArray){ doWhatever(valArray[0], function(){ res.end("Finished"); });});
Here's using wait.for
https://github.com/luciotato/waitfor
//in a fibervar result;if(foo === bar){ result = wait.for(function1,arg1);}else if(foo === baz){ result = wait.for(function2,arg2);}else{ result = wait.for(function3,arg3);};doWhatever(result, function(){ res.end("Finished");});
You need to be in a fiber (or generator) to use wait.for, but, if you have a lot of callback hell,wait.for is a good approach.