Created
March 21, 2015 23:57
-
-
Save ngryman/a6bb794295854736ce0b to your computer and use it in GitHub Desktop.
Waterfall with promises.
This file contains hidden or 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(tasks, callback) { | |
| var firstTask = tasks.shift(); | |
| return tasks.reduce(function(prevPromise, task) { | |
| return prevPromise.then(function() { | |
| var args = Array.prototype.slice.call(arguments); | |
| args.unshift(task); | |
| return makePromise.apply(null, args); | |
| }); | |
| }, makePromise(firstTask)); | |
| function makePromise(task) { | |
| var args = Array.prototype.slice.call(arguments, 1); | |
| return new Promise(function(resolve) { | |
| function resolveProxy() { | |
| console.timeEnd(task.displayName); | |
| resolve.apply(null, arguments); | |
| } | |
| args.push(resolveProxy); | |
| console.time(task.displayName); | |
| var res = task.apply(null, args); | |
| if (res) resolveProxy(res); | |
| }); | |
| } | |
| } |
This file contains hidden or 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(tasks, callback) { | |
| var firstTask = tasks.shift(); | |
| return tasks.reduce(function(prevPromise, task) { | |
| return prevPromise.then(function() { | |
| var args = Array.prototype.slice.call(arguments); | |
| args.unshift(task); | |
| return makePromise.apply(null, args); | |
| }); | |
| }, makePromise(firstTask)); | |
| function makePromise(task) { | |
| var args = Array.prototype.slice.call(arguments, 1); | |
| return new Promise(function(resolve) { | |
| args.push(resolve); | |
| var res = task.apply(null, args); | |
| if (res) resolve(res); | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment