Skip to content

Instantly share code, notes, and snippets.

@paleite
Created June 11, 2020 16:33
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 paleite/98eac3d0f4c944c5169f8d685a7bf047 to your computer and use it in GitHub Desktop.
Save paleite/98eac3d0f4c944c5169f8d685a7bf047 to your computer and use it in GitHub Desktop.
Promise.all()-timing comparison
(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