Skip to main content

Menu

System onlineAI Tutorials / 2026

AI Tutorials
Knowledge search

Recent · Popular · Tutorials

  • dart3 tutorials
  • java1 tutorial
  • Javascript5 tutorials
  • Node.js Introduction2 tutorials
  • JavascriptJavascript · Beginner · Mid
  • JavascriptJavascript · Beginner · Short
  • dartdart · General · In depth
  • JavascriptJavascript · Advanced · In depth

Find a tutorial

Tell the assistant what you want to learn. It suggests published chapters.

For example: “I want to learn Rust ownership from the start.” The conversation is kept only in this tab.

0 / 2,000 characters

Enter to send, Shift+Enter for a new line. Do not include personal information.

Chapter 16

async/await and Fetching Data

So far, you have seen promises — objects that represent a value arriving later. In this chapter you learn **async/await**, a way to write asynchronous code that looks almost like normal, step-by-step code. You will also fetch data from a web address, the most common real-world use of async/await.
Level: BeginnerLength: Mid2 min read

Read at another depth

async/await and Fetching Data

What You Will Learn

So far, you have seen promises — objects that represent a value arriving later. In this chapter you learn async/await, a way to write asynchronous code that looks almost like normal, step-by-step code. You will also fetch data from a web address, the most common real-world use of async/await.

Prerequisites

This chapter assumes you know what a promise is and how to use .then(). You should also know basic function syntax.

Two New Keywords

async is a keyword you put before a function. It means the function always returns a promise.

await is a keyword you put before a promise. It means "pause here until the promise is settled, then give me the result." You can only use await inside an async function.

Here is a promise-based example rewritten with async/await:

Code example in javascript
// Old way, with .then()
function wait() {
  return new Promise(resolve => setTimeout(resolve, 1000));
}
wait().then(() => console.log('done'));

// New way, with async/await
async function run() {
  await wait();          // pause here for 1 second
  console.log('done');
}
run();

The await version reads top to bottom, which makes it easier to follow.

Fetching Data

fetch is a built-in browser function that requests data from a web address (a URL, such as https://api.example.com/users/1). It returns a promise for the server's response. A response is an object describing what the server sent back.

Code example in javascript
async function loadUser(id) {
  const response = await fetch(`https://api.example.com/users/${id}`);
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }
  return await response.json();
}

Step by step:

  1. await fetch(...) — send the request and wait for the response headers.
  2. response.ok — a boolean that is true only when the HTTP status code is 200–299. A status code is a number the server sends, like 200 for "OK" or 404 for "not found." fetch does not throw an error on a 404, so you must check this yourself.
  3. throw new Error(...) — if the request failed, raise an error so the caller can handle it.
  4. response.json() — this reads the response body and turns the JSON text (a common data format that looks like JavaScript objects) into a real JavaScript value. It also returns a promise, so it needs await too.

Catching Errors

Errors from await are caught with a normal try/catch block, which you met earlier:

Code example in javascript
async function showUser(id) {
  try {
    const user = await loadUser(id);
    console.log(user);
  } catch (error) {
    console.log('Could not load user:', error.message);
  }
}
showUser(1);

How It Flows

Flowchart showing an async function calling fetch, awaiting the response, checking response.ok, then awaiting response.json to get the data, or throwing an error caught by try/catch.
100%
The flow of an async function that fetches data
Show diagram source
sequenceDiagram
    participant C as Caller
    participant A as async function
    participant S as Server
    C->>A: call showUser(1)
    A->>S: fetch request
    S-->>A: response (status 200)
    A->>A: check response.ok
    A->>S: response.json()
    S-->>A: parsed data
    A-->>C: return data
    Note over C,A: error? catch block runs instead

Common Mistakes

  • Forgetting await. fetch(url) without await gives you a promise, not the data. Logging it shows Promise { <pending> }.
  • Forgetting await on response.json(). You get a promise for the data, not the data.
  • Skipping the response.ok check. A 404 error will look like success and response.json() will fail confusingly.

Practice

Exercise

What does await do, and where can you use it?

Show answer

await pauses the async function until the promise settles, then gives you the settled value (or throws if the promise rejected). You can only use it inside an async function.

Exercise

fetch succeeds but the server returned status 404. Does fetch throw an error? What should you do?

Show answer

No, fetch does not throw for HTTP error statuses. You should check response.ok and throw your own error if it is false.

Spotted a mistake, or code that does not work?

Report an issue

Chapter: async/await and Fetching Data

0 / 2,000 characters

Plain text, for example: the second code sample does not compile. Do not include personal information.

You can't do that