The library that I used in Node quite often is Async ( https://github.com/caolan/async ). The last thing I checked also supports the browser, so you should be able to npm / concat / minify this in your distribution. If you use this only on the server side, you should consider https://github.com/continuationlabs/insync , which has slightly improved the Async version, and some of them have removed browser support.
One of the common patterns that I use when using conditional asynchronous calls is to populate the array with the functions that I want to use in order and pass them to async.waterfall.
I gave an example below.
var tasks = []; if (conditionOne) { tasks.push(functionOne); } if (conditionTwo) { tasks.push(functionTwo); } if (conditionThree) { tasks.push(functionThree); } async.waterfall(tasks, function (err, result) { // do something with the result. // if any functions in the task throws an error, this function is // immediately called with err == <that error> }); var functionOne = function(callback) { // do something // callback(null, some_result); }; var functionTwo = function(previousResult, callback) { // do something with previous result if needed // callback(null, previousResult, some_result); }; var functionThree = function(previousResult, callback) { // do something with previous result if needed // callback(null, some_result); };
Of course you could use promises. In any case, I like to avoid nested callbacks using async or promises.
Some of the things you can avoid by NOT using nested callbacks are collision variables, loading errors, "marching" to the right โ โ, hard-to-read code, etc.
ambrons
source share