Async await in JavaScript & React Js
What is Async/await in React
Await” only works inside the Async functions. As you know that asynchronous function tasks are never dependent on each other. They never wait to complete the first execution and run parallel. so we are talking about “Await” today in this article.
Async/await is a new way to write Asynchronous code in JS. Before Async/Await we used callbacks and promises in our code. If you never know about promises, so you need to get the concept about promises from here.
Actually, when we need to load more data from different API endpoints, we mostly fetch the data using fetch() function. As you know that fetch() is an Async function so when we call a lot of fetch() functions to get the data from different API endpoints then he never waits to complete the first fetch(). In this case, your data might be lost if you are passing data to another component state. To solve this problem we use Async/await in our code.
When we call fetch() function with the await keyword, it means that await keyword telling the async function to stop the execution until the data comes/fetched from the server.
Async functions always return a “promise” and promise makes 3 possibilities (fulfilled, pending, rejected). So basically when we fetch some data from server using API, then here we use “await” to pause the function and start the function again after data comes from Server.
async asyncFunc=()=> {
const data = await fetch(“/moviesList”);
return data;
}
Using “Await” we can conveniently handle multiple promises instead of using more .then() functions. For Error Handling, we use try, catch blocks. Here we just need to wrap the code in try block, if any error occurs during fetching of data from the server, we handle this error on catch block.
Even if we have multiple await lines, our catch block picks all the errors that occur in the code.
async asyncFunc=()=> {
try {
const response = await fetch(“/moviesList”);
const data = await response.json();
return data;
}
catch (error) {
alert(error); // catches both errors
}
}
Thanks for visit:
Please follow me on LinkedIn: https://www.linkedin.com/in/azeem-aleem-560345148/