Home > Web Front-end > JS Tutorial > How Can Promises Simplify Asynchronous XHR Requests in JavaScript?

How Can Promises Simplify Asynchronous XHR Requests in JavaScript?

Susan Sarandon
Release: 2024-12-06 20:14:16
Original
597 people have browsed it

How Can Promises Simplify Asynchronous XHR Requests in JavaScript?

How Promises Enable Asynchronous Programming with Native XHR

When working with XHR in a frontend app, it's often desirable to utilize promises for streamlined asynchronous programming. However, implementing promisified XHR without a bulky framework can prove challenging.

Understanding Native XHR

Before delving into promisification, let's review how to perform a basic XHR request using callbacks:

function makeRequest(method, url, done) {
  const xhr = new XMLHttpRequest();
  xhr.open(method, url);
  xhr.onload = function() {
    done(null, xhr.response);
  };
  xhr.onerror = function() {
    done(xhr.response);
  };
  xhr.send();
}
Copy after login

Introducing Promises with XHR

To promisify the native XHR, we leverage the Promise constructor:

function makeRequest(method, url) {
  return new Promise(function(resolve, reject) {
    const xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.onload = function() {
      if (xhr.status >= 200 && xhr.status < 300) {
        resolve(xhr.response);
      } else {
        reject({
          status: xhr.status,
          statusText: xhr.statusText
        });
      }
    };
    xhr.onerror = function() {
      reject({
        status: xhr.status,
        statusText: xhr.statusText
      });
    };
    xhr.send();
  });
}
Copy after login

Now, we can seamlessly chain and handle asynchronous XHR requests using .then() and .catch():

makeRequest('GET', 'http://example.com')
  .then(function(datums) {
    console.log(datums);
  })
  .catch(function(err) {
    console.error('Augh, there was an error!', err.statusText);
  });
Copy after login

Enhanced Functionality

We can further enhance the makeRequest function by accepting a customizable options object:

function makeRequest(opts) {
  return new Promise(function(resolve, reject) {
    // ... (code remains similar to previous example) ...
  });
}
Copy after login

This allows us to specify parameters such as POST/PUT data and custom headers:

makeRequest({
  method: 'GET',
  url: 'http://example.com',
  params: {
    score: 9001
  },
  headers: {
    'X-Subliminal-Message': 'Upvote-this-answer'
  }
});
Copy after login

In conclusion, promisifying native XHR offers a powerful means to simplify and enhance asynchronous programming in your frontend applications. Utilizing the Promise constructor along with customizable options provides a flexible and efficient approach to handling XHR requests.

The above is the detailed content of How Can Promises Simplify Asynchronous XHR Requests in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template