Last active
September 7, 2016 20:59
-
-
Save roboncode/92d4642187e392fd1d46eeb8b1a33129 to your computer and use it in GitHub Desktop.
Waterfall calls function async preventing deep nesting
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
// 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); | |
}); |
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
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