Asynchronous Execution and the Fetch API
Learn how to manage asynchronous execution in JavaScript and retrieve data from web services with the Fetch API.
Introduction
Section titled “Introduction”Use Case Diagram
Section titled “Use Case Diagram”The Use Case Diagram describes the exercise flow:
- the user starts the
hello.txtrequest, - 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.
Diagram created with Mermaid
Project File Structure
Section titled “Project File Structure”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
Sequence Diagram
Section titled “Sequence Diagram”-
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.
Diagram created with Mermaid
The Sequence Diagram describes the flow of the asynchronous request:
- when the user clicks the button,
JavaScriptusesfetch()to requesthello.txtfrom 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.
Component Diagram
Section titled “Component Diagram”Let’s see which logical components interact during fetch() execution: the browser sends an HTTP GET request, receives a Response, and updates the 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.
Deployment Diagram
Section titled “Deployment Diagram”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.
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.
Coding
Section titled “Coding”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>Hello World!In summary, the code uses async and await to make the request non-blocking:
fetch('hello.txt')starts an HTTP request,response.okverifies that the response was successful,- and
response.text()reads the file contents as text. - The
try/catchblock handles network errors or a missing file, preventing the page from freezing and allowing the DOM to be updated with the result.
Testing the Code
Section titled “Testing the Code”See the Pen fetch Hello World by Carlo (@Scocco) on CodePen.
Summary
Section titled “Summary”Knowledge Check
Section titled “Knowledge Check”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:
asyncdeclares an asynchronous function, andawaittemporarily 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
Responseobject containing status and methods for reading the body.Correct:
fetch()returns a Promise that resolves to aResponse; the body can then be read with methods such astext()orjson().
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.okindicates 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/catchlets 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
Your score
0%
0 / 0 correct answers
Answered: 0 / 0 (0%)
STICS © 2026 by Carlo Scocco is licensed under CC BY-NC 4.0