Async/Await with Koa

At the time of this writing (July 2017), KoaJS and most of its popular middleware support ES6 async/await. NodeJS had been supporting them for some time as well. Here we will see a minimal example of koa and koa-router packages using async/await.

Install the packages:

npm i koa koa-router --save

Create a JS file as follows.

var Koa = require('koa');
var router = require('koa-router');

var app = new Koa()
var api = router();

api.get('/hello', async (ctx) => {
    ctx.response.body = await f1()
});

app
  .use(api.routes())
  .use(api.allowedMethods());

app.listen(8080);

async function f1() {
    return new Promise((resolve, reject) => {
        let message = {
            greeting: "Hello",
            planet: "World"
        }

        resolve(message)
    })
}

This shows how to use an async method for routing.

Save and run the file.

Then, run curl to test it out.

curl -v localhost:8080/hello

Verify that the response content type is application/json; charset=utf-8 and the body is:

{"greeting":"Hello","planet":"World"}