Intermediate · 12 min
Promises and async/await
Wait for asynchronous results and handle rejected promises.
Await a result
An async function returns a promise. await pauses that function until the promise settles; it does not block the browser thread. The playground runs each program as a module, where top-level await is available.
async function getName() { return "Ada"; }
const name = await getName();
console.log(name);Output
Ada
Catch a rejection
A rejected promise becomes a thrown error at await. Use try/catch around the awaited operation when you can recover. These examples use local promises instead of network requests.
async function load() { throw new Error("Unavailable"); }
try { await load(); } catch (error) { console.log(error.message); }Output
Unavailable
Put it into practice
- Predict each result before running the example.
- Complete the coding task, then explain why your solution works.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Wait for the total
Await calculate() before displaying total.
Add await when assigning the result of calculate().