Using Promise.all

Take array of fetch functions, fetch all values (from URLs) and receive array of the results

by Konstantin Rouda

JavaScript

/* Fetching URL */
function fetchURL(url) { // fetches data from specified url, using Promise
  return new Promise(function (resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    
    xhr.addEventListener("load", function (e) {
          debugger;
        if (xhr.status < 400 && (xhr.statusText === "OK" || xhr.statusText === "")) {
          resolve(xhr.response);
        }  else {
          reject(new Error("Request Error: " + xhr.statusText));
        }
    });
    
    xhr.addEventListener("error", function(e) {
        reject(new Error("Request Error: " + xhr.statusText));
    });
    
    xhr.send(null); // we're making GET request, we're not sending any data, so we set parameter as null
  });
};


 
    var arrOfPromises = [
    fetchURL("https://jsonplaceholder.typicode.com/posts/1"),
    fetchURL("https://jsonplaceholder.typicode.com/users"),
    fetchURL("https://randomuser.me/api/")];
    
    
    Promise.all(arrOfPromises).then(function(results) {
       debugger;
       return JSON.parse(results);
    }).then(function(resultsArr) {
        // parsed array of values
        debugger;
    }).catch(function(err) {
    	 debugger;
    });