‘Async & Await’ is the process that works to use “promise” in a more comfortable way. The advantage of “async & await ” is that it is easy to understand and use.
Async Function: Async function starts with async keyword.
Await: The keyword await makes JavaScript wait until that promise settles and returns its result.Let’s see an example how we can use async & await. Here is an array of customer object.
Now we will create a method to get the customer firstname using forEach loop. There is a function setTimeout() which is used to show time delay as a symbol of asynchronization.
Here is another function that create customer and push to the array. The function works as a promise.
Now what will happen for the following code?
That’s the output. The third customer is’nt in the customer as it way delayed 2000 ms.
Here we can solve this by async & await. We will make the getCustomer() function wait until createCustomer() has done it’s work.
Then everything works fine.
That’s how async & await works. Happy Coding!!!!