JavaScript Asynchronous Programming with JavaScript Understanding Promises Handle Multiple Promises with Promise.all

Begana Choi
PLUS
Begana Choi
Courses Plus Student 13,122 Points

promises.js:19 XHR failed loading: GET "https://en.wikipedia.org/api/rest_v1/page/summary/Anatoly%20Ivanishin".

I have some error issues that always with wiki url. and before I use Promise.all() everything worked but not perfectly, for example, one of the Promise got error for the same reason. and now I can't use Promise.all() at all. (also I checked previous replies and nothing worked for me) what can I do?

2 Answers

Nikola Ivanovic
Nikola Ivanovic
8,785 Points

Hi! I had the same problem I resolved it by following this discussion here. In function getProfiles you need to insert conditional statement like this:

 if (person.name == "Anatoly Ivanishin") {
       person.name = "Anatoli_Ivanishin"
   }

So the final example of the getProfiles function would be :

function getProfiles(json) {
   const profiles = json.people.map(person => {

   if (person.name == "Anatoly Ivanishin") {
       person.name = "Anatoli_Ivanishin"
   }
   return getJSON(wikiUrl + person.name);
  });
  return Promise.all(profiles);
}

The name in the JSON file on the notify.org was 'Anatoly' instead 'Anatoli' like the name on Wikipedia. Hope this helps.

I'm looking for the rsolution to this that doesn't require a hard-coded conditional statement. This method is a hack not a fix. Has anyone found one, I've tried this (which doesn't work):

function getProfiles(json) {
  const profiles = json.people.map( person => {
    const profile = getJSON(wikiUrl + person.name)
      .then(profile => profile)
      .catch(e => e);
  });
  return Promise.all(profiles)
    .then(profiles)
    .catch( function(err) {
      console.log('Promise was rejected', err);
      return(profiles);
    });
}
Brendan Moran
Brendan Moran
13,743 Points

Use Promise.allSettled().

function getWikiProfiles(data) {
  const profiles = data.people.map(person => {
    return getJSON(wikiUrl + person.name);
  });
  return Promise.allSettled(profiles);
}

function generateHTML(data) {
  //console.log(data);
  data.forEach(person => {
    if (person.status === 'fulfilled') {
      person = person.value;
      const section = document.createElement('section');
      peopleList.appendChild(section);
      section.innerHTML = `
        <img src=${person.thumbnail.source}>
        <h2>${person.title}</h2>
        <p>${person.description}</p>
        <p>${person.extract}</p>
      `;
    }
  });