Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.