Created
November 7, 2018 15:22
-
-
Save hh54188/580a281c4af39f34eb234f80be8721f5 to your computer and use it in GitHub Desktop.
promise sequentially
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://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