Created
January 31, 2019 17:39
-
-
Save spadin/ffafbc60cacebd0d468e4a4a03d0da10 to your computer and use it in GitHub Desktop.
Run promises sequentially using Array#reduce
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
// https://css-tricks.com/why-using-reduce-to-sequentially-resolve-promises-works/ | |
const sayHelloIn = (seconds) => () => new Promise((resolve, reject) => { | |
setTimeout(() => { | |
console.log(`Hello ${seconds} seconds later.`) | |
resolve(); | |
}, seconds * 1000); | |
}); | |
const sequentially = async (fns) => { | |
return fns.reduce(async (acc, fn) => { | |
await acc; | |
return fn(); | |
}, Promise.resolve()); | |
} | |
sequentially([ | |
sayHelloIn(1), | |
sayHelloIn(2), | |
sayHelloIn(1) | |
]).then(() => { | |
console.log('done') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment