JavaScript Fetch API using Async/Await
In this video we see how JavaScript fetch
API can be written using async/await
.
Code
// using fetchfetch("https://api.github.com/users/deekshasharma").then(response => response.json()).then(jsonData => console.log(jsonData))// using async/awaitasync function getGithubData(){let response = await fetch("https://api.github.com/users/deekshasharma")return response.json();}getGithubData().then(jsonData => console.log(jsonData))
Full Transcript
In this video, we will see how JavaScript fetch
API can be written using async/await
. Let's open Chrome dev tools using Command + Option + I
, on your Mac.
We will go to the sources panel and create a snippet right here. Let's rename it to fetch-async-await.js
. We will be using GitHub users API to fetch the data,
given a GitHub username. Normally we would use fetch API like this: We call fetch()
with URL that we are trying to fetch the data from. It returns a promise that
results to a response object. So we grab that using .then()
method, and we get the JSON
from that response by calling the method .json()
, which also returns a promise,
that we grab inside another .then, and finally print the JSON
data in a console.log
. Let's run it. And there we go.
We have the data from GitHub. Now, what if we want to use async/await
to rewrite this fetch
API. async/await
nothing but a syntactic sugar on top of JavaScript promise.
We will write an async
function, getGithubData
. The keyword async
denotes that this is an asynchronous function and may or may not contain an await
expression.
This function may contain more than one await expressions too. So let's grab inside a response, variable the results from a fetch
call. Note that we are using the keyword, await
,
the response is then converted to JSON
, by calling .json()
method and return it back to the caller.
A few things before we move ahead. getGithubData
is an async
function that always returns a promise. If the return value of this function is not explicitly a promise,
it will be automatically wrapped inside a promise. You can only use await
keyword inside an async
function. If you use it otherwise, it's going to give you syntax error.
await
keyword here before this fetch
expression waits for a promise from the fetch call and causes the entire async
function to pause the execution until the promise is either
fulfilled or rejected. It pretty much simplify the use of promise so that they behave synchronously, which is more intuitive. We''ll call our async function getGithubData
,
and since it returns a promise, we will grab it inside .then()
method. We get the JSON
data that can be logged inside console.log
. Let's comment out the fetch
API code and run
it again. As you can see, we got the GitHub data. So now you know how you can rewrite the fetch API code using async/await
. That's all I wanted to cover in this video. Thanks for watching.