I want to await two promises that run in parallel. I do not want to await each promise serially (which works but is slower).
For that reason I thought I could create two promises first to get them rolling, say two network requests, then await them and be able to catch errors in a catch block. That assumption seems to be incorrect as I get a warning when running this example code.
- Why is that?
- How do I best run two or multiple network requests in parallel otherwise with elegant code?
- Why does Typescript not warn me that the catch-block will not catch rejections?
async function testMultipleAwait() {
try {
const aPromise = new Promise((resolve) => {
setTimeout(() => resolve('a'), 200);
});
const bPromise = new Promise((_, reject) => {
setTimeout(() => reject('b'), 100);
});
const a = await aPromise;
const b = await bPromise;
} catch (e) {
console.log('Caught error', e);
}
}
testMultipleAwait();
Does NOT result in "Caught error" output, instead I get
tsc test-try-catch-await.ts && node test-try-catch-await.js
(node:31755) UnhandledPromiseRejectionWarning: b
(node:31755) 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: 1)
(node:31755) [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.
Caught error b
(node:31755) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)