Home >Web Front-end >JS Tutorial >How to Promisify Native XHR Requests Using JavaScript?
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.
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(); }
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(); }); }
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); }); }
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); });
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!