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);
}
Read More :-
Help Needed Plz
Need help in raising fund to buy a Mechanical Keyboard. This pandemic has affected my family badly so can't ask my DAD for it. Please Help Me.
This was something short I wanted to share!
⚡Happy Coding.
Top comments (4)
I didn't know that can use the 'catch' to an await function.
I've been used only try-catch block for catching errors. and I've just known that only works.
Thanks for your post :)
You can use catch on a promise and it will return another promise.
You can use await on a promise to wait for the result.
So everything is ok with the example, even if with the await keyword you can use a try/catch block to catch the error rejected by a promise.
Thank you :DD
Welcome!