Menu

React, etc. Tech Stack

React, Flux, GraphQL, Hack, HHVM...? All of this and more!

Koa 2, the Node.js framework engineered for async/await

The scene for Node.js developers for a general purpose framework has been fairly stable. Express.js continues to be the number one option, but it is growing a bit long in the tooth and the future of Express remains murky.

Express 5 is in the cards, but still in limbo. Koa.js is the other common option, but with it's focus on the somewhat cumbersome generator syntax it's not been widely adopted. This has left the Node.js community in somewhat of a stagnant state regarding core web frameworks.

But with Koa 2.0 in development and maturing slowly, it looks to be a fresh of breath air for Node.js development. The async/await syntax is more welcoming to developers and adoption is picking up and Koa 2.0 is built on this very same concept.

Async/await allows developers to write asynchronous code in a syntax that looks synchronous, this makes it easier to reason about. A quick code snippet of a Koa 2.0 application demonstrates what this means in practise:

// Koa application is now a class and requires the new operator.
const app = new Koa();

// uses async arrow functions
app.use(async (ctx, next) => {
  try {
    await next(); // next is now a function
  } catch (err) {
    ctx.body = { message: err.message };
    ctx.status = err.status || 500;
  }
});

app.use(async ctx => {
  const user = await User.getById(ctx.session.userid); // await instead of yield
  ctx.body = user; // ctx instead of this
});

The new version remains in development and there is no definite schedule for launching it. The team is waiting for Node.js to ship with a V8 version that supports Async/Await by default.

The best way to follow up on the development of Koa v2 is on GitHub with the Koa v2 roadmap ticket as well as the ongoing documentation effort for the new version.

Written by Jorgé on Sunday November 27, 2016

Permalink -

« Web Components and SEO - React vs. Svelte, the JavaScript build-time framework »