Skip to content

Instantly share code, notes, and snippets.

@roboncode
Last active September 7, 2016 20:59
Show Gist options
  • Save roboncode/92d4642187e392fd1d46eeb8b1a33129 to your computer and use it in GitHub Desktop.
Save roboncode/92d4642187e392fd1d46eeb8b1a33129 to your computer and use it in GitHub Desktop.
Waterfall calls function async preventing deep nesting
// usage example
var wf = waterfall({count: 0})
wf([
function(data) {
data.count++;
},
function(data) {
data.count++;
// to stop the cascade, return anything
// return 'Stop cascade';
},
function(data, done) {
data.count++;
setTimeout(done, 1000); // can be async
// to stop the cascade, return anything
// setTimeout(done, 1000, 'Stop cascade');
}
], function(result) {
console.log(result);
});
function waterfall(data) {
return function cascade(callbacks, done) {
if (callbacks.length) {
var fn = callbacks.shift();
var match = fn.toString().match(/function\s?\(.*,/gm);
if (!match) {
var result = fn(data);
if (result === undefined) {
cascade(callbacks, arguments[1]);
} else {
arguments(result);
}
}
else {
fn.apply(null, [data, function (result) {
if (result === undefined) {
cascade(callbacks, done);
} else {
done(result);
}
}]);
}
} else {
done(data);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment