Async/Await
One of the most recent additions to the JavaScript world of asynchronous programming is the async/await duo. They are the refined version of promises.
The ‘async’ keyword is added before a function during its definition. Any function defined this way returns a promise. If any other value is returned, it is wrapped within a resolved promise.
The ‘await’ keyword can only be used within a function that is defined using ‘async’. This waits till the promise is resolved before any assignments. In the for the above ‘new’ function:
When multiple promises are “awaited”, they are executed one after the other, when they resolved. This is used mainly when the execution of promise isn’t very time consuming. They are much easier to be analysed when chained than regular promises.
For example consider an example of multiple file reads:
The above code looks much cleaner and readable than using promises or callbacks.
Async/await makes an asynchronous code look like and behave a synchronous one, though it is non-blocking. It is particularly useful when a condition depends on the result of a resolved promise or when result of a resolved promise is a temporary component. It is much more easier to debug async/await than the promises or callbacks. All this makes it a very powerful tool when used properly.