Search⌘ K
AI Features

Creating Asynchronous HTTP Requests in JavaScript

Explore how to create asynchronous HTTP requests using the fetch method in JavaScript. Understand promises, chaining operations, handling JSON data, and managing errors to build efficient web applications.

Since synchronous requests block the calling process until their result is received, only asynchronous HTTP requests should be used when building a web application. However, asynchronous code can be tricky to write and to understand, since statements won’t be executed in a linear and sequential fashion like with synchronous operations.

The fetch() method

The best way to send asynchronous HTTP requests in JavaScript is to use the fetch() method. Here is its general usage form.

Markdown
// Sends an asynchronous HTTP request to the target url
fetch(url)
.then(() => {
// Code called in the future when the request ends successfully
})
.catch(() => {
// Code called in the future when an errors occurs during the request
});

You might encounter JavaScript code that uses an object called XMLHttpRequest to perform HTTP operations. This is a more ancient technique now replaced by fetch(). ...