Skip to content

Instantly share code, notes, and snippets.

@gordey4doronin
Last active August 26, 2020 05:39
Show Gist options
  • Save gordey4doronin/217ba8e2e040c1e309d766ea1aa45d3e to your computer and use it in GitHub Desktop.
Save gordey4doronin/217ba8e2e040c1e309d766ea1aa45d3e to your computer and use it in GitHub Desktop.
Sequential async/await VS concurrent Promise.all
const waitFor = (ms) => new Promise(r => setTimeout(r, ms));
const startSequential = async () => {
for (const num of [3, 2, 1]) {
await waitFor(1000 * num);
console.log(num + ' ' + new Date().toISOString());
}
console.log('Done Sequential');
}
const startConcurrent = async () => {
await Promise.all([3, 2, 1].map(async (num) => {
await waitFor(1000 * num);
console.log(num + ' ' + new Date().toISOString());
}));
console.log('Done Concurrent');
}
const startConcurrentThrow = async () => {
await Promise.all([3, 2, 1].map(async (num) => {
if (num == 2) { throw 'boom'; }
await waitFor(1000 * num);
console.log(num + ' ' + new Date().toISOString());
}));
console.log('Done Concurrent Throw Catch');
}
const startConcurrentThrowCatch = async () => {
await Promise.all([3, 2, 1].map(async (num) => {
try {
if (num == 2) { throw 'boom'; }
await waitFor(1000 * num);
console.log(num + ' ' + new Date().toISOString());
} catch {
// ignore
}
}));
console.log('Done Concurrent Throw Catch');
}
// Try each of example separately
// startSequential();
// startConcurrent();
// startConcurrentThrow();
// startConcurrentThrowCatch();

startSequential()

3 2019-12-06T02:33:23.816Z
2 2019-12-06T02:33:25.821Z
1 2019-12-06T02:33:26.827Z
Done Sequential

startConcurrent()

1 2019-12-06T02:33:32.811Z
2 2019-12-06T02:33:33.811Z
3 2019-12-06T02:33:34.808Z
Done Concurrent

startConcurrentThrow()

(node:30205) UnhandledPromiseRejectionWarning: boom
(node:30205) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)
(node:30205) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
1 2019-12-06T02:33:42.137Z
3 2019-12-06T02:33:44.136Z

startConcurrentThrowCatch()

1 2019-12-06T02:33:58.555Z
3 2019-12-06T02:34:00.550Z
Done Concurrent Throw Catch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment