CCA Prep

Lesson 5.1Lesson 18 of 24

Promises and async/await

Given a scenario, apply asynchronous programming concepts.

Promises and async/awaitSeveral independent promises: what shoulda failure do?Fail at the firsterrorPromise.allall values, or thefirst errorCollect everyoutcomePromise.allSettled{ status, value |reason } eachFirst to settle winsPromise.racee.g. a timeoutFirst success winsPromise.anyAggregateError ifall fail

Key points

  1. 1An async function always returns a promise: return x fulfils it with x, throw rejects it.
  2. 2await pauses only the async function it is in. The caller and the rest of the program keep running.
  3. 3What a then callback returns becomes the next step's value. Forget the return and the next step gets undefined without waiting.
  4. 4Start independent work first, then wait for it together: Promise.all, allSettled, race or any, depending on what a failure should do.
  5. 5A rejection is caught only where it is awaited: try/catch around a promise you return without await catches nothing.
What the exam guide checks here

Objective wording from the exam guide (English).

  • 5.1.K1Callbacks, promises, then/catch/finally chains and what each returns
  • 5.1.K2async functions and await: what they return and when code after await runs
  • 5.1.K3Promise.all, allSettled, race and any: results and failure behaviour
  • 5.1.S1Choose the asynchronous code that meets a requirement (order, concurrency, failures)

Lock it in

Answer scenario questions on this topic. Every option comes with an explanation.

Practise 5.1 · 12 questions