# Async and Await
One of the features added in ES6 was async
and await
. The combination of these keywords lets us use asynchronous features like fetch
inside a function but in a synchronous way.
Here is an example.
async function getData() {
let url = 'https://www.example.com/items/';
let response = await fetch(url);
// now we have the actual response object in our response variable
let data = await response.json();
// now we actually have the JSON data inside the data variable
console.log(data);
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
This works by wrapping the asynchronous call in a Promise and making the rest of the function wait for the result before continuing. Without the await
the variables response
and data
would not work properly. response
would hold the Promise object which is the fetch waiting for a response. The next line, where we call the json()
method would fail because that is not a valid method to call on a fetch or promise object.
The await
is what solves the problem and makes the code wait for the result of the fetch()
and the json()
methods.