Module lessons (4/4)
Errors in asynchronous code
Asynchronous operations fail differently from synchronous ones: the error does not arrive immediately, it arrives "later", when the Promise enters the rejected state. Let's look at the two main tools.
try/catch with await
When you put await before a Promise that fails, the error is rethrown as a
normal exception: you catch it with try/catch.
async function safeRead() {
try {
const r = await fetch('/api/cose');
if (!r.ok) throw new Error('HTTP ' + r.status);
return await r.json();
} catch (err) {
console.error('network error:', err.message);
return null;
}
}It is the most readable pattern: you write the "happy path" linearly, and handle everything in a single block.
.catch on a Promise
In chained style:
fetch('/api/cose')
.then((r) => r.json())
.then((data) => console.log(data))
.catch((err) => console.error(err));.catch catches any error thrown along the preceding chain.
Promise.all fails on the first rejection
const ps = [Promise.resolve(1), Promise.reject(new Error('no')), Promise.resolve(3)];
try {
const r = await Promise.all(ps);
} catch (err) {
console.log(err.message); // 'no'
}The other Promises keep running in the background, but Promise.all "settles" on the first error.
If you want the results of all of them (including failures), use Promise.allSettled:
const outcomes = await Promise.allSettled(ps);
// [{ status: 'fulfilled', value: 1 },
// { status: 'rejected', reason: Error('no') },
// { status: 'fulfilled', value: 3 }]Try it
Define `readOrFallback(p, fallback)` async: try to await the Promise p; if it is rejected, return fallback.
Show hint
try { return await p; } catch { return fallback; }
Solution available after 3 attempts
Review exercise
Define `allOrNothing(promises)` async: use Promise.all. If at least one fails, return the empty array []. Otherwise return the values.
Show hint
try { return await Promise.all(promises); } catch { return []; }
Solution available after 3 attempts