Skip to content

Instantly share code, notes, and snippets.

@qubyte
Created October 10, 2013 09:55
Show Gist options
  • Save qubyte/6915879 to your computer and use it in GitHub Desktop.
Save qubyte/6915879 to your computer and use it in GitHub Desktop.
Nest one asynchronous function in another. Both functions are optional. MIT licence.
function nest(before, after) {
'use strict';
if (typeof before !== 'function') {
// Only after is defined, so just return it.
if (typeof after === 'function') {
return after;
}
// Neither function is defined, so return a function that just executes a callback.
return function (callback) {
callback();
};
}
// before exists, so execute it first.
return function (callback) {
before(function (err) {
if (err) {
return callback(err);
}
// If newFunc is defined, execute it after before.
if (typeof after === 'function') {
return after(callback);
}
// If newFunc is not defined, just execute the callback after before.
callback();
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment