In promises, the object creation starts the execution of asynchronous functionality. Here await only blocks the code execution within the async function. Code Pen
The async keyword, which you put in front of a function declaration to turn it into an async Function that returns a Promise object.
await keyword accepted only inside the async functions.
In the below example, the f2 method is not declared with the async keyword which returns a value. The f3 method returns a promise when declared with the async keyword.
await keyword causes async function execution to pause until the promise is settled(fulfilled or rejected).
How async function perform with and without await keyword?
Case1: Perform without await keyword Code Pen
Case2: Perform with the await keyword Code Pen
Hope this provides an understanding of the async/await function.
Using promise chain vs async/await Code Pen
We know how the callback turned into Promises then promise chain and now async/await. If a function using a Promise chain, only the promise chain is asynchronous not the entire function. But in async/await the entire function is asynchronous.
How the same code work with Async/await approach?
In the awaitWay method, we modified all the promise chains to individual function calls with the await keyword. This means the entire function will wait until the function having the await keyword will get resolved.
When seeing the output here first the value 40 prints and then the statement prints “is this really run in Asynchronous way? Yes ”. It was printed vice versa in Promise chains
Hope it will give a basic understanding of Async/await, Please write your questions for any doubts or corrections.
Whatever we learned as of now from ES features enough to start the ReactJS. Let’s start our next topic about React Basics.
Next topic: Learn React from scratch