ES6 Fetch
Whether you've been using Javascript for a while, or a beginner just learning the basics of asynchronous functions in Javascript, you've most likely used the ES6 Fetch API to retrieve data from a URI. Here is an example of using fetch()
to get user information from the Github API:
const getUser = name => {
fetch(`https://api.github.com/users/${name}`)
.then(response => response.json())
.then(data => console.log(data))
};
//get user data
getUser('yourUsernameHere');
The above code isn't bad. It is fairly readable and it does function correctly. However, notice the .then()
function, which supports a callback function for resolving the fetch function. You can imagine that as you start chaining more .then()
's, the code will get increasingly harder to read. This can lead into what is often referred to as "callback hell", or nested callbacks, and can easily lead to bad performance or bugs.
Refactor with async/await
ES8 brought about the async
function and await
keyword. Using async
and await
doesn't change how asynchronous functions operate. These features are just syntactical sugar that makes things more readable, and in turn makes handling the return of a Promise object more seamless. They also make asynchronous code look more like synchronous code. Below is the same fetch()
call using async
and await
:
const getUser = async (name) => {
let response = await fetch(`https://api.github.com/users/${name}`);
let data = await response.json();
return data;
}
//get user data
getUser('yourUsernameHere')
.then(console.log(data));
Overall, this syntax is much easier to read and there is no longer a need for large .then()
blocks. Keep in mind though, that in order to call a function using the await
keyword, it must be within the async
function. There's a lot more that can be covered in this topic, but I thought this would be a simple explanation to implementing async
and await
in your Javascript code.
Top comments (0)