0% found this document useful (0 votes)
12 views19 pages

DevX JS - W3C9 - Async - Await

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views19 pages

DevX JS - W3C9 - Async - Await

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Javascript

Async/Await
Review
Review
● JSON format: ● APIs
○ Key:Value pairs only! ○ API Requests
○ Only double quotes! ○ API Keys
○ All keys have (double) quotes! ○ OpenWeather
○ No functions! ○ Building an app with API
○ Curly braces for objects.
○ Square brackets for arrays.
Async/Await
Async/Await
async and await are two new keywords in
JS. They help you write requests. getUsers();

Remember how we talked about async function getUsers(quantity = 10) {


promises? How your code could execute var url =
while a promise is open, and “then” some `https://randomuser.me/api/?results=${qu
more code runs when it resolves? antity}`;
var response = await fetch(url);
async/await let you wait for the promise var data = await response.json();
before executing the rest of your code! var results = data.results;
console.log(results);
}
Old and New

var url = getUsers();


`https://randomuser.me/api/?results=5`;
async function getUsers( ) {
fetch(url) var url =
.then(function (response) { `https://randomuser.me/api/?results=5`;
return response.json(); var response = await fetch(url);
}) var data = await response.json();
.then(function (data) { console.log(data);
console.log(data); }
});
How to Implement Async/Await
1. Add the keyword “async” in front of a
function name/definition. keyword declare function
2. Inside the function, you can now use
the “await” keyword. async function getUsers(quantity) {
3. Only use “await” when you make a
request/promise. var url =
4. You also need to set a variable to hold `https://randomuser.me/api/?results=${qu
the product of the promise. Without antity}`; keyword
it, you won’t have a variable that can
access that information. var response = await fetch(url);

} store response in variable


then do something with it…
Note: Fetch
With fetch, when you receive the response, you must convert the data into JSON format. This
is a separate step (and also a promise). Other request options might not have this step.

getUsersSync (); getUsersAsync ();

function getUsersSync (quantity = 10) { async function getUsersAsync (quantity = 10) {


var url = var url =
`https://randomuser.me/api/?results= ${quantity}` `https://randomuser.me/api/?results= ${quantity}`
; ;
var response = fetch(url) var response = await fetch(url); to json
.then(function (response) { to json var data = await response.json();
return response.json(); var results = data.results;
})
.then(function (data) { console.log("async", results);
console.log("sync", data.results); }
});
}
fetch("/login")

Why Async?
.then(function (res) {
return res.json();
})
.then(function (loginData) {
Why did we bother to learn two ways to fetch("/getClasses/" + loginData.userId )
write requests and promises? .then(function (res) {
return res.json();
})
Async is good when you have several,
.then(function (class) {
dependent API calls. Eg: fetch ("/getStudents/" + class.classId )
.then(function (res) {
1. Getting your account info return res.json();
})
2. Getting a list of your classes
.then(function (students) {
3. Getting a list of your students in
// Now you have everything!
those classes. // Login, class, and students!
});
You can’t get your classes until the app });
});
knows who you are, and can’t get your
// This is not real code! Just an example.
students until you know classes.
fetch("/login")

Callback Hell
.then(function (res) {
return res.json();
})
.then(function (loginData) {
In the example on the right, we see a fetch("/getClasses/" + loginData.userId )
concept jokingly called “callback hell”. .then(function (res) {
return res.json();
})
An API call makes another API call, and
.then(function (class) {
you end up with multiple nested function fetch ("/getStudents/" + class.classId )
calls and responses. This gets messy, as .then(function (res) {
you can see on the right. return res.json();
})
.then(function (students) {
Async await lets you do them all in the
// Now you have everything!
same scope. This is easier. // Login, class, and students!
});
});
});
// This is not real code! Just an example.
Just Async/Await
With async/await, we can rewrite multiple callbacks into cleaner code.

With this methodology,


the code will sit and wait
async function start() {
for the first promise var loginResponse = await fetch("/login");
before going to the next var loginData = await loginresponse .json();
line.
var classResponse = await fetch("getClasses/" + loginData.userId);
var classData = await classResponse .json();
The code will perform
similarly, but is much var studentsResponse = await fetch("/getStudents/" + classData.classId);
easier to read. var studentData = await studentsResponse .json();

// Now you have everything!


// Login, class, and students!
}
When To Not Async/Await
Some developers use async/await for everything. It’s not always the right choice.

For a single API call, either method is fine. There’s not much code, and the async feature doesn’t
offer much benefit.

If you are making multiple, non-dependent api calls (eg, getting the weather AND news- separate
topics), async/await is actually WORSE! It is faster to use JS to make two requests at the same
time, rather than waiting for the first to finish!

For NOW I recommend picking either one and getting comfortable with it. Later in your career
you will be more worried about fast load times. But for now we are just learning how to do stuff!
async/await
async/await
We are going to re-factor a request into
async/await: getUsersSync(10);

1. First make a new function. function getUsersSync(quantity) {


2. Add the async keyword in front of it. let url =
3. Put the fetch( ) call inside the function. `https://randomuser.me/api/?results=${quantity}`;

4. Put await in front of fetch( ). fetch(url)

5. Store the value in a variable. .then(function (response) {


return response.json();
6. Use .json( ) to convert that variable to
})
JSON.
.then(function (data) {
7. Put await in front of that.
console.log("sync", data.results);
8. Store the value in another variable.
});
9. console.log the second variable!
}
RapidApi
RapidApi
RapidApi is an online service that collects APIs and allows you to access them.

It helps streamline the API KEY generation process, and has a searchable list of all the APIs it has
available.

The best part is that it has lots of example code that you can copy/paste to try out!
RapidApi
RapidApi
1. Go to https://rapidapi.com/hub, and
sign up for the service.
2. Look on the website for free APIs!
(Like really free. Some require a credit
card. Let’s stick to really free.)
3. When you find that free api, pick a
request type on the left.
4. Find some sample code on the right.
Set it to “javascript - fetch”.
5. Share in the chat the javascript object
you get!
6. Explore the APIs, which are useful?
Share in the chat!
Q&A

You might also like