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 trial

JavaScript Asynchronous Programming with JavaScript Exploring Async/Await Combine Async/Await with Promises

Samuel Kleos
seal-mask
.a{fill-rule:evenodd;}techdegree
Samuel Kleos
Front End Web Development Techdegree Student 13,728 Points

How 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
Steven Parker
231,275 Points

You 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
seal-mask
.a{fill-rule:evenodd;}techdegree
Samuel Kleos
Front End Web Development Techdegree Student 13,728 Points

What 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
Steven Parker
231,275 Points

The 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).