How it works...

Using await within an async function is equivalent to using then in a Promise chain. The difference is that instead of the result being passed as an argument to the callback function, it is resolved as an expression. This expression can be assigned to the constant result. The value is then available for the rest of the block, and not limited to the body of a callback function.

This is pretty cool! Previously getting results from asynchronous code required the use of callbacks and methods in the Promise API. Now, with the async and await keywords, we can write code without nesting, making it easier to read and understand, while maintaining compatibility with the Promise API.

Get ECMAScript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.