liveBook · Manning

Async function

As explained in Secrets of the JavaScript Ninja, Third Edition

The async keyword marks a function whose return value is wrapped in a promise and whose thrown errors reject that promise.

An async function is declared with the async keyword, which works with function declarations and arrow functions. Every call returns a promise, and await is permitted inside the function. section 8.2.2 section 8.2.3

The function’s return and error behavior becomes its promise’s outcome:

  • Returning a value resolves the promise with that value; returning a promise uses the promise resolution algorithm. section 8.2.3
  • Throwing a value rejects the promise, so callers can handle failures with promise rejection handling. section 8.2.3
  • Await inside the function affects when and how its returned promise resolves; it does not interrupt the caller’s flow. section 8.2.3
Listing 8.8 Using an async function to fetch and parse JSON
const fetchJson = async (url: string) => { #A
  const response = await fetch(url); #A
  if (!response.ok) { #A
    throw new Error(`Status code ${response.status}`); #A
  } #A
  return response.json(); #A
}; #A

try {
  console.log(
    await fetchJson( #B
      "https://jsonplaceholder.typicode.com/posts/1", #B
    ), #B
  );
} catch (error) { #C
  console.error(`Request failed: ${error}`); #C
} finally {
  console.log("Request finished");
}

A fetchJson function awaits a request, throws on an unsuccessful response, and returns parsed JSON; callers handle failure with try/catch. section 8.2.3

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines value resolution and error rejection, then demonstrates their use in a fetch-and-parse workflow.
Examples
Uses a function returning a string and a fetchJson request that checks response status before parsing JSON.
What you can do after
Apply async functions to return promise results and turn thrown errors into promise rejections.
How it connects
Connects promises, await, ECMAScript modules, and try/catch error handling.

Also explained in

Compare how 3 books explain async function →

Related concepts

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