Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
propagate async callback usefull when using async.waterfall with mongoose
// 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
You can’t perform that action at this time.