liveBook · Manning

Async/await

As explained in Secrets of the JavaScript Ninja, Second Edition

A language keyword that pauses an async function until a promise settles and then evaluates to the promise's result or throws its rejection.

async/await lets an async function pause for an asynchronous result without blocking the JavaScript engine. The async keyword marks the function; await marks each task whose result it needs. Promises and generators provide the underlying model, without requiring you to write their coordination boilerplate. section 6.4.1 section 6.4

(async function (){
  try {
    const ninjas = await getJSON("data/ninjas.json");
    const missions = await getJSON(missions[0].missionsUrl);

    console.log(missions);
  }
  catch(e) {
    console.log("Error: ", e);
  }
})()


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":1},{\"line\":0,\"ch\":6}],[{\"line\":2,\"ch\":19},{\"line\":2,\"ch\":24}],[{\"line\":3,\"ch\":21},{\"line\":3,\"ch\":26}],[{\"line\":2,\"ch\":19},{\"line\":2,\"ch\":24}],[{\"line\":3,\"ch\":21},{\"line\":3,\"ch\":26}]]"}
!@%STYLE%@!

This example awaits JSON requests in sequence and handles errors with try/catch. section 6.4.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains the keywords’ roles and their generator-and-promise model, with a short JSON example.
Examples
Uses sequential JSON requests for ninja and mission data, with try/catch error handling.
What it assumes
Builds on generators and promises, whose pause, resume, and settlement behavior supply the underlying model.
What you can do after
Apply async/await to sequence dependent JSON requests without blocking and handle failures with try/catch.
How it connects
Links async/await to generators, promises, and nonblocking asynchronous execution.

Also explained in

Compare how 17 books explain async/await →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.