Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@npatmaja
Created May 5, 2015 07:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npatmaja/3e1f2c92e1a6d9d0250e to your computer and use it in GitHub Desktop.
Save npatmaja/3e1f2c92e1a6d9d0250e to your computer and use it in GitHub Desktop.
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