Async-Await
Explore how async-await in ES2017 enhances JavaScript by allowing you to write asynchronous functions that return promises. Learn to use the await operator for sequential and parallel execution of asynchronous tasks, handle errors with try-catch blocks, and improve code readability and performance.
The ability to write asynchronous functions is a major update in ES2017.
What are the asynchronous functions?
Asynchronous functions are functions that return a promise. We denote them by using the async keyword.
When loadData returns an object, the return value is wrapped into a promise. As this promise is resolved, the then callback is executed, console logging the response.
When loadData is called with the argument 0, an error is thrown. This error is wrapped into a rejected promise, which is handled by the catch callback.
In general, return values of an async function are wrapped into a resolved promise, except if the return value is a promise itself. In the latter case, the promise is returned. Errors thrown in an async function are caught and wrapped into a rejected promise.
The await operator
Await is a prefix operator standing in front of a promise.
As long as the promise behind the await operator is pending, await blocks execution.
As soon as the promise is resolved, await returns the fulfillment value of the promise.
As soon as the promise is rejected, await throws ...