JavaScript theorytheory 0/50 · 0%
Async · easy

14. async / await

Sequential-looking async code and error handling.

An `async` function always returns a promise. `await` pauses that function until the awaited promise settles, without blocking the thread. Errors surface as exceptions, so `try/catch` works normally.

async function getBalance(client, addr) {
  try {
    return await client.getBalance(addr);
  } catch (err) {
    console.error("rpc failed", err);
    return 0n;
  }
}

Awaiting inside a loop serialises the calls; use `Promise.all` when the requests are independent.

Check your understanding

  1. 1. What does an `async` function return?

  2. 2. How do you catch an awaited rejection?

  3. 3. What is wrong with `await` inside a loop over independent calls?