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

Georg Ekeberg
Georg Ekeberg
5,702 Points

Program breaks when on of the promises are rejected. (Namespelling discrepancy issue.)

Since Wikipedia spells Anatoly's name with an I at the end, I get a 404 error on that specific promise. This gives me the following error:

Error at XMLHttpRequest.xhr.onload (promises.js:15)

How do I make sure that the program works, even if this happens?

3 Answers

Brendan Moran
Brendan Moran
13,743 Points

Use Promise.allSettled(). The following code works, it's simply going to skip over the rejected promise:

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>
      `;
    }
  });
Sean Ball
Sean Ball
10,501 Points

where exactly is getWikiProfiles being called?

Steven Parker
Steven Parker
207,003 Points

This issue is due to two 3rd-party API's having a disagreement about spelling. :see_no_evil: Code that would handle this kind of thing in a generic way would be rather complex.

But if you don't mind applying a temporary fix for these specific cases, see the code posted by another student in reponse to this other question