Emulating Synchronous Style with async and await

One of the most powerful new features in Node.js 8 is the introduction of async functions. Part of the 2017 ECMAScript draft specification, async functions allow you reap the benefits of Promises for simplifying code flow while structuring your code in a more natural way.

The key is that unlike a regular function, which always runs to completion, an async function can be intentionally suspended midexecution to wait on the resolution of a Promise. Note that this does not violate the central maxim that JavaScript is single-threaded. It’s not that some other code will preempt your async function, but rather that you choose to unblock the event loop to await a Promise.

An example should clarify. ...

Get Node.js 8 the Right Way 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.