Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
JavaScript promises provide an efficient way to fire off and keep track of multiple asynchronous operations with the Promise.all
method. Promise.all
is useful when your program needs to wait for more than one promise to resolve.
Alternative solutions
Using forEach()
Below is another way you could write the generateHTML
function using the forEach
array iteration method.
forEach()
executes its callback function once for each array element, whereas map()
does the same but creates a new array with the results of executing its callback on every item in the original array.
function generateHTML(data) {
data.forEach( person => {
const section = document.createElement('section');
peopleList.appendChild(section);
// Check if request returns a 'standard' page from Wiki
if (person.type === 'standard') {
section.innerHTML = `
<img src=${person.thumbnail.source}>
<h2>${person.title}</h2>
<p>${person.description}</p>
<p>${person.extract}</p>
`;
} else {
section.innerHTML = `
<img src="img/profile.jpg" alt="ocean clouds seen from space">
<h2>${person.title}</h2>
<p>Results unavailable for ${person.title}</p>
${person.extract_html}
`;
}
});
}
Promise.all()
Below is another way you might define a list of promises, and execute other tasks when they are all resolved:
const func1 = getJSON('...');
const func2 = getJSON('...');
Promise.all([func1, func2])
.then(results => {
console.log('Array of results', results);
})
.catch(error => {
console.error(error);
})
Resources
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up