Async functions compared to promises

suggest change

async and await are syntax built on promises; they do not replace the Promise type. Calling an async function always returns a promise. A returned value fulfills that promise, while a thrown exception rejects it.

The same sequential workflow can be expressed with a promise chain or with await:

function createUnicornWithPromises() {
  return fetch("/unicorn.json")
    .then((response) => {
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      return response.json();
    })
    .then((unicorn) => fetch("/new/unicorn", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ unicorn }),
    }))
    .then((response) => {
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      return response.json();
    })
    .then((result) => result.success);
}

With async and await, the control flow is linear:

async function createUnicorn() {
  const currentResponse = await fetch("/unicorn.json");
  if (!currentResponse.ok) {
    throw new Error(`HTTP ${currentResponse.status}`);
  }

  const unicorn = await currentResponse.json();
  const newResponse = await fetch("/new/unicorn", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ unicorn }),
  });

  if (!newResponse.ok) {
    throw new Error(`HTTP ${newResponse.status}`);
  }

  const result = await newResponse.json();
  return result.success;
}

await pauses only the current async function until its operand settles; it does not block the JavaScript thread. If the operations are independent, start them together and await Promise.all() instead of awaiting them one at a time.

Handle errors where the program can recover or add useful context. Otherwise, let the returned promise reject so the caller can handle it:

try {
  const created = await createUnicorn();
  console.log({ created });
} catch (error) {
  console.error("Could not create the unicorn", error);
}

Avoid starting an async operation without awaiting or returning its promise unless it is deliberately detached and has its own rejection handler.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents