Skip to content

Instantly share code, notes, and snippets.

@spadin
Created January 31, 2019 17:39
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 spadin/ffafbc60cacebd0d468e4a4a03d0da10 to your computer and use it in GitHub Desktop.
Save spadin/ffafbc60cacebd0d468e4a4a03d0da10 to your computer and use it in GitHub Desktop.
Run promises sequentially using Array#reduce
// 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