Created
January 26, 2022 22:35
-
-
Save DiegoVictor/fa4c6525c5366d77c866f4b5685ff6b7 to your computer and use it in GitHub Desktop.
Generate promises from an array, run the promises in sequence, starting the next one once the previous finish
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
async function call(value) { | |
const label = `Promise ${value}`; | |
console.time(label); | |
return new Promise((resolve) => { | |
setTimeout(() => { | |
console.timeEnd(label); | |
resolve(); | |
}, Math.floor(9 * Math.random() + 1) * 1000); | |
}); | |
} | |
[1, 2, 3].reduce(async (promise, item) => { | |
return promise.then(() => call(item)); | |
}, Promise.resolve()); | |
// Output: | |
// Promise 1: 7.009s | |
// Promise 2: 9.002s | |
// Promise 3: 2.013s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment