Async & await explained in short
Async & await basically just syntactic sugar on top of promises. Here is my latest post and very short and amazing explanation of Async and await.
If you use the async keyword before the function definition, you can then use await within the function. Await gives you the power to pause the function in a non-blocking way until the promise is settled.
If the promise fulfils, you get the value back. If not, the rejected value is thrown. Here is a perfect example for you below:-
async function fetchUsers( endpoint ) {
const res = await fetch( endpoint );
const data = await res.json();
const usernames = data.map( user => user.username);
console.log(usernames);
}
fetchUsers( 'https://jsonplaceholder.typicode.com/users');
/*
["Bret", "Antonette", "Samantha", "Karianne", "Kamren", "Leopoldo_Corkery", "Elwyn.Skiles", "Maxime_Nienow", "Delphine", "Moriah.Stanton"]
*/
First, the given endpoint is fetched. At this point, the function pauses until the fetch Promise is fulfilled.
After that, the response is read and parsed as JSON. Because we await that too, JSON()
is a Promise aswel, we pause the function again until it is fulfilled.
When that's all done we can use the data retrieved and for example map it and log it to the console.
What is one of the awaits gets rejected?
=> We can add a catch()
to every single await because they're just normal Promises!
With the catches added to the awaits, our function will look like the example below.
async function fetchUsers( endpoint ) {
const res = await fetch( endpoint ).catch(e => console.error(e.message));
const data = await res.json().catch(e => console.error(e.message);
const usernames = data.map( user => user.username);
console.log(usernames);
}
This was something short I wanted to share!
⚡Happy Coding.
UI Developer | A Learner
Very Well Explained, Thanks!
Comments (2)