Wait up for async/await, it's great!

async/await is a new javascript feature that allows you to wrap asynchronous code, so it appears to be synchronous. This makes your code easier to read and easier to reason about.

Eelke Boezeman

--

The await keyword halts the code execution cursor until the Promise is resolved. As you don't need to use callback functions anymore to deal with asynchronicity, you can now write your code as if all operations are synchronous which is A Good Thing™:

  • ‘synchronous’ (downward) execution is easier to read and therefore comprehend
  • no callback functions means less boiler plate and less indentation
  • a single, shared function scope removes the need to ‘pass data around’ — it’s just there

A trivial example

The power of async/await truly shines in situations where there are multiple asynchronous operations that need to be composed in to a single result.

Consider the following functionality:

  • fetch a user and their posts (in parallel, to speed up execution)
  • get the comments on those posts
  • parse the posts with the comments

Although the example is trivial, data needs to be passed around which increases complexity. This is can implemented by:

  • storing the data in the shared, outer function scope, or;
  • passing the data along from one async.waterfall callback to the next, or;
  • using async/await to create a single function scope

Promises with async/await

You can implement the above functionality with async/await quite elegantly.

Trivial example implemented using Promises with async/await

Note:

  • Whenever you use await, the surrounding function needs to be declared to be async.
  • Use try/catch to handle any Promise that fails within the async function.

Promises, without async/await

Note:

  • Promises are nested because earlier data (ie. user and posts) needs to be accessible to be used later.
  • The code has more boiler plate and more indentation.

Callbacks with async library

Note:

  • 'Passing along data' is cumbersome and so is error-handling (if (err) return done(err); much lately?)
  • There are other control flow libraries that offer similar solutions.
  • Even more boiler plate and indentation.

Mere callbacks

Note:

  • Executing getUser and getPosts in parallel is pretty ugly without a proper abstraction like async.parallel or a similar library

Why await?

With async/await, you can write code that is easier to read and reason about. It's native Javascript so it's a matter of time before it's widely supported. To start using it today, use NodeJS 7 with --harmony. It's also supported by Chrome and in any case, you can always use babel to transpile it into regular ol' javascript.

--

--

Eelke Boezeman

Web developer & architect @purplescout ♦ co-founder @peerby ♦ class of 2013 Techstars London ♦ class of 2012 @rockstartaccel ♦ Atheist ♦ Wanna-be agnost