JAVASCRIPT   140

xhr.js

Guest on 26th July 2021 04:40:26 PM

  1. // @see https://gomakethings.com/promise-based-xhr/
  2.  
  3. export const makeRequest = function (url, method = 'GET') {
  4.  
  5.     // Create the XHR request
  6.     var request = new XMLHttpRequest();
  7.  
  8.     // Return it as a Promise
  9.     return new Promise(function (resolve, reject) {
  10.  
  11.         // Setup our listener to process compeleted requests
  12.         request.onreadystatechange = function () {
  13.  
  14.             // Only run if the request is complete
  15.             if (request.readyState !== 4) return;
  16.  
  17.             // Process the response
  18.             if (request.status >= 200 && request.status < 300) {
  19.                 // If successful
  20.                 resolve(request);
  21.             } else {
  22.                 // If failed
  23.                 reject({
  24.                     status: request.status,
  25.                     statusText: request.statusText,
  26.                     request: request
  27.                 });
  28.             }
  29.  
  30.         };
  31.  
  32.         // Setup our HTTP request
  33.         request.open(method || 'GET', url, true);
  34.  
  35.         // Send the request
  36.         request.send();
  37.  
  38.     });
  39. };
  40.  
  41. const jsonDecodeIfPossible = function(str) {
  42.     try {
  43.         return JSON.parse(str);
  44.     } catch(e) {
  45.         return str;
  46.     }
  47. }
  48.  
  49. export const makeJSONRequest = async function(url, method = 'GET') {
  50.     try {
  51.         const request = await makeRequest(url, method);
  52.         return jsonDecodeIfPossible(request.responseText);
  53.     } catch(e) {
  54.         return jsonDecodeIfPossible(e.request.responseText);
  55.     }
  56. }

Raw Paste


Login or Register to edit or fork this paste. It's free.