...

/

Creating Asynchronous HTTP Requests in JavaScript

Creating Asynchronous HTTP Requests in JavaScript

Learn how to retrieve data from a web server through HTTP requests.

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.

Press + to interact
// 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(). ...

Under