Last active
April 13, 2016 15:09
-
-
Save DannyDelott/f4b676bdde38f6be2a6a1254d9f8be1a to your computer and use it in GitHub Desktop.
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
var sum = 0; | |
var add5Async = () => { | |
return setTimeoutAsync(1000) | |
.then(add5.bind(null, sum)) // pure function, bind global variable as input | |
.then(setSum); // side-effect at the end | |
}; | |
asyncReduce([ add5Async, add5Async, add5Async ]) | |
.then(() => { console.log('sum:', sum); }) | |
.catch((e) => { console.log(e); } ); | |
function add5(number) { return number + 5; } | |
function setSum (_) { sum = _; } | |
function setTimeoutAsync(delay) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
try { resolve(); } | |
catch (e) { reject(e); } | |
}, delay); | |
}); | |
} | |
function asyncReduce(promises) { | |
return promises.reduce((chain, fn) => chain.then(fn), Promise.resolve()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment