Skip to main content
eLearner.app
Module 7 · Lesson 4 of 428/32 in the course~12 min
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.

JS
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:

JS
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

JS
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:

JS
const outcomes = await Promise.allSettled(ps);
// [{ status: 'fulfilled', value: 1 },
//  { status: 'rejected', reason: Error('no') },
//  { status: 'fulfilled', value: 3 }]

Try it

Exercise#js.m7.l4.e1
Attempts: 0Loading…

Define `readOrFallback(p, fallback)` async: try to await the Promise p; if it is rejected, return fallback.

Loading editor…
Show hint

try { return await p; } catch { return fallback; }

Solution available after 3 attempts

Review exercise

Exercise#js.m7.l4.e2
Attempts: 0Loading…

Define `allOrNothing(promises)` async: use Promise.all. If at least one fails, return the empty array []. Otherwise return the values.

Loading editor…
Show hint

try { return await Promise.all(promises); } catch { return []; }

Solution available after 3 attempts