Async and Await in JavaScript
The async keyword
First of all, we have the async
keyword, which you put in front of a function declaration to turn it into an async function. An async function is a function that knows how to expect the possibility of the await
keyword being used to invoke asynchronous code.
What does this mean?
Let us understand the above statement in a simpler manner, You see programming language like JavaScript execute all its function in a single-threaded wise operation, that means that all the code which you have written in your JS compiler will execute the line of entire written code in a linear manner or say top to bottom from the first row to last. Now the word async
means that it can halt the normal control execution flow of the execution and make the execution available only after a certain set of programming code is finished its execution.
Example for ASYNC function:
let hello = async function() { return "Hello" };
hello();
The await keyword
The real advantage of async functions becomes apparent when you combine it with the await keyword — in fact, await
only works inside async functions. This can be put in front of any async promise-based function to pause your code on that line until the promise fulfills, then return the resulting value. In the meantime, other code that may be waiting for a chance to execute gets to do so.
You can use await
when calling any function that returns a Promise, including web API functions.
What does this mean?
So far we have learned that the async function can halt the normal flow execution of the program and it wait for some particular code to finish its execution before it can execute its own code, Now the await function will let know that the function to remain in the hold unless previous code has finished its execution.
Example for ASYNC and AWAIT function:
fetch('coffee.jpg')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
} else {
return response.blob();
}
})
.then(myBlob => {
let objectURL = URL.createObjectURL(myBlob);
let image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
})
.catch(e => {
console.log('There has been a problem with your fetch operation: ' + e.message);
});
Let us take a better understanding by calling API in react using async and await
Async / Await in React
async componentDidMount() {
const response = await fetch(`https://api.com/v1/ticker/?limit=10`);
const json = await response.json();
this.setState({ data: json });
}
In the above example, it can be seen that we created a function(Lifecycle method in react) with the async
keyword that shows that it will hold its execution useless some line of code has finished its execution. The await
keyword before the fetch function means that function is gonna wait until and fetch function has fetch
the API link data, and after this the code again going to wait has the data has to converted to JSON format for displaying the data in normal format.
More Effective way to write code in ASYNC and AWAIT
Add a try/catch
block:
async componentDidMount() {
try {
const response = await fetch(`https://api.com/v1/ticker/?limit=10`);
const json = await response.json();
this.setState({ data: json });
} catch (error) {
console.log(error);
}
}
In the above example, it can be noticed that adding the try/catch
block to the above code makes the code cleaner to read and to catch an error if occurred during the process. So the above all code is been kept and the user try
block and catching of the error is been kept under the catch
block. To make sure everything goes well as per the process.
Here in the above example, the main code is been kept under the try block, and as usual, the await keyword plays its role of waiting till the code fetch the data from the API link and meanwhile if there happens to be an error generating, the catch block part will be executed and this process also helps in the code execution to be faster as well.
Conclusion
And there you have it — async/await provides a nice, simplified way to write async code that is simpler to read and maintain. async/await works much better when put under try/catch block. Even with browser support being more limited than other async code mechanisms at the time of writing, it is well worth learning and considering for use, both for now and in the future.