Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
In this video, you will convert many of the project's promise chains to async/await.
Resources
Examples of async/await patterns
// Anonymous async function
(async function() {
const response = await fetch('...');
})();
// Async function assignment
const getData = async function() {
const response = await fetch('...');
};
// Arrow functions
const getData = async () => {
const response = await fetch('...');
};
// Async Function as an argument
btn.addEventListener('click', async () => {
const response = await fetch('...');
});
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
In your project folder,
open the file async-await.js.
0:00
And make sure to update the script tag and
index.html to point to async-await.js.
0:04
So this new file contains the same global
variables we've worked with all along,
0:11
also the generateHTML function that
generates the mark up for each profile and
0:16
the addEventListener method.
0:20
Looking at where we left off in
the previous stage with fetchAPI,
0:23
you can see that we're calling fetch in
the EventListener to kick off an Ajax
0:26
request, then following a sequence of
then methods to manage and distribute
0:29
the return data to other functions in
the program like getProfiles for example.
0:34
So what we're going to do now
is write one async function
0:38
that will handle each of these tasks.
0:43
Then, all we'd need to do is call
the function here in the event listener,
0:46
passing it the URL to fetch.
0:49
First, we'll declare an async
function named, getPeopleInSpace.
0:55
This function is going to first make
a fetch request to the open notify API,
1:02
then use those results to make fetch
requests to the Wikipedia API.
1:07
Remember, the async keyword is used for
the function declaration,
1:11
so let's tag this function with async.
1:16
The function also takes the parameter
URL for the URL to fetch.
1:20
In the body of the function,
1:25
we'll start by making the first network
request using the fetch method.
1:26
It will be to the open notify API to
get the names of the people and space.
1:29
So I'll declare a variable
named people response
1:34
to capture the value returned from
fetch passing it URL as its argument.
1:39
You know that fetch returns a promise, and
1:46
that the keyword await is
used to handle the promise.
1:49
So let's include await
before the fetch method.
1:52
The await keyword is going to wait for
a resolved promise returned by fetch.
1:57
Then it's going to get the fulfillment
value out of the promise and
2:03
assign it to peopleReponse.
2:07
Now, let's parse the response
from Fetch to JSON.
2:10
Create a new variable named peopleJSON and
2:13
assign it peopleResponse.json.
2:18
Once again, we'll await the JSON data
2:23
by including await in front
of peopleResponse.json.
2:26
So far our getPeopleInSpace
function is going to fetch the URL,
2:30
await the response, then it's going to
read the response and await the JSON.
2:35
Next, let's continue by making
the next set of network requests.
2:41
This is where we'll map over the array
of objects stored in peopleJSON and
2:45
fetch data from the Wikipedia API based
on the return names of people in space.
2:49
Like earlier,
create a variable named profiles and
2:54
we want to iterate over the people
property of each JSON object.
2:59
So we'll set it to peopleJSON.people.map,
3:04
the map call back will take the parameter
person to represent each person in space.
3:08
In the body of the call back,
we'll follow the same steps as earlier.
3:16
Declare a variable named profileResponse
3:20
that awaits the response
object from fetch,
3:25
passing at the Wikipedia URL which
is stored in the variable wikiUrl.
3:30
Then I'll concatenate the value of
a person object's name property on
3:36
each iteration with + person.name.
3:40
After that,
declare a variable named profileJSON,
3:44
and here we await a resolved premise
3:51
from profileResponse.JSON.
3:56
Remember, any code that calls await needs
to be wrapped in an async function,
4:01
otherwise the function
will produce an error.
4:07
map is performing an async operation
on every item in the array, and
4:09
assigning the results to profiles.
4:14
So we'll also need to mark
the callback function of map as async.
4:17
Next, just like in the previous stage,
4:27
let's display the spacecraft
each astronaut is on.
4:29
We know that the data is available in the
first API call we make to the open notify
4:33
API under a property named craft.
4:37
So in the map method,
we'll pull that data out and
4:40
save it in a variable named
craft with person.craft.
4:43
Then we'll combine the craft data
with the astronaut profiles' data
4:48
by returning an object.
4:53
Inside the object,
I'll once again use the spread operator
4:54
to copy all the properties from the
profileJSON object onto this new object,
4:58
along with the craft property and value.
5:04
So like the getProfiles function we wrote
earlier, getPeopleInSpace is going to
5:07
return the array of promise objects
captured in the variable profiles.
5:12
So now, let's use promise.all to wait
on all of those individual promises
5:17
then join them into a single promise that
gets resolved when all are fulfilled.
5:22
Below the map method,
let's return Promise.all(),
5:27
passing it the variable profiles.
5:32
The value of Promise.all() is
the result of each of the map calls.
5:35
So the function is going to wait for
the aggregated promise to be resolved into
5:41
a single promise before
it returns the data.
5:46
So now, down in the event listener,
5:49
there are a couple of ways to approach
calling the getPeopleInSpace function, and
5:52
passing the returned promise
to the generateHTML function.
5:56
We could use async await or
change promises.
6:00
For example, I'll use async await first
by declaring a variable named astros for
6:03
astronauts which will store
the results of getPeopleInSpace,
6:10
passing it the open notify API end
point stored in the variable astrosUrl.
6:15
Since getPeopleInSpace returns a promise,
we'll need to await
6:21
the result of that promise by including
the await keyword in front of it.
6:25
Now remember, you use the await keyword
only inside functions marked as async.
6:30
So let's not forget to include async in
front of addEventListener's callback.
6:35
Now we can invoke generateHTML and
pass it the value of astros.
6:41
So now generateHTML gets all the data it
needs to begin generating the markup for
6:48
each astronaut profile.
6:52
And to remove the button
once the data loads,
6:54
I'll once again call
remove on event.target.
6:57
So far we've written asynchronous
promise based code that except for
7:04
maybe the keywords async and await,
looks much like regular synchronous code.
7:09
Sure there appears to be a little more
code than in the previous examples.
7:14
But because it reads closer to synchronous
code, it's easier to follow and
7:17
understand, especially for
those less familiar with promises.
7:22
And we'll refactor some of this
code in a later video, too.
7:26
All right, let's test our code.
7:29
Over in the browser I'll refresh and
click the View button.
7:31
And all the people in space
profiles display as expected, good.
7:36
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