Skip to content

Instantly share code, notes, and snippets.

@hh54188
Created November 7, 2018 15:22
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 hh54188/580a281c4af39f34eb234f80be8721f5 to your computer and use it in GitHub Desktop.
Save hh54188/580a281c4af39f34eb234f80be8721f5 to your computer and use it in GitHub Desktop.
promise sequentially
// https://hackernoon.com/functional-javascript-resolving-promises-sequentially-7aac18c4431e
// https://decembersoft.com/posts/promises-in-serial-with-array-reduce/
function delay() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('RESOLVED')
resolve()
}, 1000 * 1)
})
}
const arr = new Array(10).fill(delay)
const resultPromise = arr.reduce(function (prevPromise, currentPromise) {
return prevPromise.then(prevResults => {
return currentPromise().then(curResult => {
return [...prevResults, curResult]
})
})
}, Promise.resolve([]))
resultPromise.then(results => {
console.log(results)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment