Skip to content

Asynchronous Execution and the Fetch API

Learn how to manage asynchronous execution in JavaScript and retrieve data from web services with the Fetch API.

The Use Case Diagram describes the exercise flow:

  • the user starts the hello.txt request,
  • then the system waits for the response asynchronously and displays the content in the DOM, or informs the user about a network error or a missing file.
flowchart LR Utente(["🚶 User"]) subgraph Sistema ["Asynchronous application with Fetch API"] U1(["Start the file request"]) U2(["Display the contents of hello.txt"]) U3(["Display an error message"]) U1 -.-> U2 U1 -.-> U3 end Utente --> U1 classDef actor fill:#1e3a8a,stroke:#3b82f6,color:#fff,stroke-width:2px; classDef usecase fill:#2563eb,stroke:#1d4ed8,color:#fff,stroke-width:2px; classDef system fill:#f8fafc,stroke:#64748b,stroke-width:2px,color:#0f172a; class Utente actor; class U1,U2,U3 usecase; class Sistema system;

Diagram created with Mermaid

Before writing the code, make sure to create both files in the same working folder:

  • Directoryasync-fetch-project/
    • index.html Main page containing the HTML structure and JavaScript script
    • hello.txt Example text file to retrieve asynchronously
  • Purpose: Illustrates the chronological order of events when the user starts a fetch() request and the browser waits for the file contents.

  • Reading note: Time flows vertically from top to bottom.

sequenceDiagram actor Utente participant Browser as Browser participant JS as JavaScript (fetch) participant Server as Web Server participant DOM as HTML Page Utente->>DOM: Click the "Load hello.txt" button DOM->>JS: Start the asynchronous function JS->>Browser: await fetch("hello.txt") Browser->>Server: Request hello.txt with HTTP GET Server-->>Browser: Return the file or an error Browser-->>JS: Return the Response object alt File found JS->>DOM: Read the text with response.text() DOM-->>Utente: Display the content in #output else File not found or network error JS->>DOM: Set the error message DOM-->>Utente: Display the error on the page end

Diagram created with Mermaid

The Sequence Diagram describes the flow of the asynchronous request:

  • when the user clicks the button, JavaScript uses fetch() to request hello.txt from the server.
  • After receiving the Response, the code reads the text and updates the page content; if an error occurs, it displays an appropriate message to the user.

Let’s see which logical components interact during fetch() execution: the browser sends an HTTP GET request, receives a Response, and updates the DOM.

flowchart TD subgraph Browser ["Browser (Client)"] DOM["DOM Element (#output)"] JS["Async JS Function (loadMessage)"] FETCH["Fetch API Engine"] end subgraph Server ["Web Server"] FILE["Text File (hello.txt)"] end DOM -->|"1. Click event"| JS JS -->|"2. await fetch(hello.txt)"| FETCH FETCH -->|"3. HTTP GET request"| FILE FILE -->|"4. Response with text"| FETCH FETCH -->|"5. Return Response"| JS JS -->|"6. output.textContent = text"| DOM

Diagram created with Mermaid

In practice, when the user clicks the button, the browser executes the JavaScript function that starts fetch(). The request is sent to the server, which returns a Response; the code then reads the content and inserts it into the DOM. The key point is that the browser does not freeze: it continues responding to events while waiting for the server response.

Let’s see where the files reside during real execution or in an environment such as CodePen/OneCompiler: the code runs in the browser (client), while hello.txt is located on the web server.

flowchart LR subgraph Client ["Client: User's Browser"] subgraph Sandbox ["Sandbox / iFrame Environment"] HTML["HTML Interface & DOM"] ENGINE["JavaScript Engine (V8)"] end end subgraph ServerHost ["Web Server / File Host"] TXT["Text file: hello.txt"] end HTML -->|Run the script| ENGINE ENGINE -->|1. Request: Fetch HTTP GET| TXT TXT -->|2. Response 200: Hello World!| ENGINE ENGINE -->|3. Update output.textContent| HTML

Diagram created with Mermaid

In this diagram, the browser is the client: it executes HTML and JavaScript, while the hello.txt file resides on the web server. The fetch() request originates in the browser, the server responds with a 200 OK status, and the JavaScript code updates the page content in the DOM.

Below is the contents of the two files:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Async Fetch Introduction</title>
</head>
<body>
<button onclick="loadMessage()">Load "Hello World"</button>
<!-- Minimal container where the text is displayed -->
<div id="output">Waiting for a click...</div>
<script>
// 1. 'async' makes the function asynchronous
async function loadMessage() {
const output = document.getElementById('output');
try {
// 2. 'await fetch' downloads the resource without blocking
const response = await fetch('hello.txt');
// 3. Check whether the file was found (e.g. 200 OK)
if (!response.ok) {
throw new Error('File not found!');
}
// 4. 'await' waits for the response body to be converted to text
const text = await response.text();
// 5. Insert the text into the DOM (without alert)
output.textContent = text;
} catch (error) {
// Handle network problems or missing files
output.textContent = 'Error: ' + error.message;
}
}
</script>
</body>
</html>

In summary, the code uses async and await to make the request non-blocking:

  • fetch('hello.txt') starts an HTTP request,
  • response.ok verifies that the response was successful,
  • and response.text() reads the file contents as text.
  • The try/catch block handles network errors or a missing file, preventing the page from freezing and allowing the DOM to be updated with the result.

See the Pen fetch Hello World by Carlo (@Scocco) on CodePen.

The answers to the quizzes on this page are saved in your browser's local storage and remain stored between visits

What does asynchronous programming allow you to do?

  • Block the browser until a request completes.
  • Wait for slow operations without preventing the rest of the code from running.

    Correct: asynchronous operations avoid blocking the interface while waiting for network responses or other future results.

  • Execute all instructions simultaneously in parallel on the CPU.

What does a Promise represent in JavaScript?

  • The HTML text returned by a web page.
  • A function that updates the DOM directly.
  • The future result of an asynchronous operation.

    Correct: a Promise can still be pending, or it can be fulfilled with a value or rejected with an error.

What is the purpose of async and await?

  • Convert an HTTP request into a synchronous request.
  • Allow Promise handling to be written more readably.

    Correct: async declares an asynchronous function, and await temporarily pauses the function until the Promise resolves.

  • Prevent any error from occurring during a request.

What does a fetch() call return after receiving the server response?

  • The parsed JSON content directly.
  • Always a string containing the page text.
  • A Response object containing status and methods for reading the body.

    Correct: fetch() returns a Promise that resolves to a Response; the body can then be read with methods such as text() or json().

When does response.ok have the value true?

  • When the server is reachable, even if it returns a 404 error.
  • When the response HTTP status is between 200 and 299.

    Correct: response.ok indicates a successful HTTP response, regardless of its body format.

  • When the response body has been read successfully with text().

What is the purpose of try/catch in a fetch() call?

  • Prevent the browser from sending unsuccessful HTTP requests.
  • Handle errors from the request or response-reading process.

    Correct: try/catch lets you intercept exceptions and display a message or perform alternative behavior.

  • Automatically convert the response text into HTML.

Quiz progress

0 / 0 questions answered (0%)

0 correct answers