Created
June 11, 2020 16:33
-
-
Save paleite/98eac3d0f4c944c5169f8d685a7bf047 to your computer and use it in GitHub Desktop.
Promise.all()-timing comparison
This file contains hidden or 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 sleep(ms, msg) { | |
console.log(`Executing '${msg}'`); | |
return new Promise((resolve) => | |
setTimeout(() => { | |
console.log(`Resolving '${msg}'`); | |
resolve(msg); | |
}, ms) | |
); | |
} | |
const serial = "Promises in serial (5s + 2s + 3s)"; | |
const parallel = "Promises in parallel (5s + 2s + 3s)"; | |
/** | |
* The following will run in serial. | |
* All promises will start and resolve serially and in order. | |
* | |
* The next will only start once the previous has resolved. | |
* | |
* Pros: Useful when the resolved value in one Promise is required in a | |
* following promise | |
* Cons: Slow | |
*/ | |
console.time(serial); | |
const a = await sleep(5000, "π #1 - 5s"); | |
const b = await sleep(2000, "πΊ #2 - 2s"); | |
const c = await sleep(3000, "π #3 - 3s"); | |
console.log({ a, b, c }); | |
console.timeEnd(serial); | |
/** | |
* The following will run in parallel. | |
* All promises will start in order and resolve in parallel, not necessarily | |
* in order. | |
* | |
* The resulting array will be in order, so destructuring will mirror the | |
* array passed to `Promise.all` | |
* | |
* Pros: Fast | |
* Cons: TypeScript requires explicit typing of each resolved value. One | |
* rejected Promise will cancel all other remaining promises. | |
*/ | |
console.time(parallel); | |
const [e, f, g] = await Promise.all([ | |
sleep(5000, "π #4 - 5s"), | |
sleep(2000, "π #5 - 2s"), | |
sleep(3000, "πΆ #6 - 3s"), | |
]); | |
console.log({ e, f, g }); | |
console.timeEnd(parallel); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment