Skip to content

Instantly share code, notes, and snippets.

@DannyDelott
Last active April 13, 2016 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DannyDelott/f4b676bdde38f6be2a6a1254d9f8be1a to your computer and use it in GitHub Desktop.
Save DannyDelott/f4b676bdde38f6be2a6a1254d9f8be1a to your computer and use it in GitHub Desktop.
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