Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSamuel Kleos
Front End Web Development Techdegree Student 13,674 PointsHow many times do you need to declare `async`?
Here an async function is defined:
async function createProfiles(astrosUrl) {
const response = await fetch(astrosUrl);
const peopleJSON = await response.json();
const profiles = peopleJSON.people.map( async person => {
const craft = person.craft;
const profileResponse = await fetch(wikiUrl+person.name);
const profileJSON = await profileResponse.json()
return {...profileJSON, craft}
})
return Promise.all(profiles);
}
Then once again async is applied to an event listener:
btn.addEventListener('click', async (event) => {
event.target.textContent = "Loading...";
const astros = await createProfiles(astrosUrl);
generateHTML(astros);
event.target.remove();
});
If you just invoked createProfiles(astrosUrl)
without specifying it inside an event listener would it still perform its tasks asynchronously?
If so why do you need to declare the event listener callback as 'async' when invoking 'createProfiles(astrosUrl)`?
See below:
createProfiles(astrosUrl)
1 Answer
Steven Parker
231,271 PointsYou are only allowed to use "await" inside of a function that has been declared "async". A program error will occur if it is omitted.
Samuel Kleos
Front End Web Development Techdegree Student 13,674 PointsSamuel Kleos
Front End Web Development Techdegree Student 13,674 PointsWhat I donβt understand is why do we need to await createProfiles(astrosUrl) in the event listener. The return line of the function contains a Promise.all() which awaits the completion of all the operations in the function anyway?
Steven Parker
231,271 PointsSteven Parker
231,271 PointsThe promise by itself doesn't cause the code to wait, it is in the "pending" state. Using await causes the code to pause until it it resolved (or rejected).