Home >Web Front-end >JS Tutorial >How to Promisify Native XHR Requests Using JavaScript?

How to Promisify Native XHR Requests Using JavaScript?

DDD
DDDOriginal
2024-12-06 06:31:121005browse

How to Promisify Native XHR Requests Using JavaScript?

How to Promisify Native XHR

Background

In modern frontend development, promises have become an essential tool for managing asynchronous operations. While many frameworks provide built-in mechanisms for promisification, it's possible to achieve this functionality with native code as well. This guide demonstrates how to transform native XHR (XMLHttpRequest) requests into promises.

Step 1: Define a Request Function with Callbacks

Begin by creating a basic XHR request function that uses callbacks:

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

Step 2: Introduce Promise Construction

To transform this function into a promisified version, leverage the promise constructor:

function makeRequest(method, url) {
  return new Promise(function (resolve, reject) {
    var 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();
  });
}

Step 3: Enhance with Parameters and Options

To improve the flexibility of the request function, introduce parameters for method, url, and an optional options object:

function makeRequest(opts) {
  return new Promise(function (resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open(opts.method, opts.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
      });
    };
    if (opts.headers) {
      Object.keys(opts.headers).forEach(function (key) {
        xhr.setRequestHeader(key, opts.headers[key]);
      });
    }
    var params = opts.params;
    if (params && typeof params === 'object') {
      params = Object.keys(params).map(function (key) {
        return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
      }).join('&');
    }
    xhr.send(params);
  });
}

Usage

With the promisified makeRequest function, XHRs can be performed seamlessly as asynchronous operations:

makeRequest({
  method: 'GET',
  url: 'http://example.com'
})
.then(function (datums) {
  return makeRequest({
    method: 'POST',
    url: datums.url,
    params: {
      score: 9001
    },
    headers: {
      'X-Subliminal-Message': 'Upvote-this-answer'
    }
  });
})
.catch(function (err) {
  console.error('Augh, there was an error!', err.statusText);
});

Alternative Approach

An alternative to promisification is to use the fetch API, which provides built-in support for promises. However, keep in mind that fetch may not be supported in all browsers and may require a polyfill.

The above is the detailed content of How to Promisify Native XHR Requests Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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