Created
May 5, 2015 07:25
-
-
Save npatmaja/3e1f2c92e1a6d9d0250e to your computer and use it in GitHub Desktop.
propagate async callback usefull when using async.waterfall with mongoose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// to propagate async callback | |
// usefull when using async.waterfall | |
// with mongoose | |
async.waterfall([ | |
task1(), | |
task2(), | |
task3() | |
], callFinalCallback()); | |
function task1() { | |
return function (next) { | |
MyModel1.find(propagateCallback(next)); | |
} | |
} | |
function task2() { | |
return function (model1, next) { | |
MyModel2.find(propagateCallback(next, model1)); | |
} | |
} | |
function task3() { | |
return function (model2, model1, next) { | |
MyModel.find(function (err, data) { | |
next(null); // call final callback | |
}); | |
} | |
} | |
function propagateCallback () { | |
var args = []; | |
var callback; | |
for (var i = 0; i < arguments.length; i++) { | |
args.push(arguments[i]); | |
} | |
if (typeof args[0] === 'function') { | |
callback = args.shift(); | |
} else { | |
throw new Error('no callback to propagate'); | |
} | |
return function (err, data) { | |
if (err) { | |
return callback(err); | |
} | |
args.unshift(data); | |
args.unshift(null); | |
return callback.apply(null, args); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment