Roman Baida
Roman Baida

Reputation: 51

Is it required to use async functions in koa framework?

I started learn koa.js and on koa documentation I found such demo code:

const Koa = require('koa');
const app = new Koa();

app.use(async ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);

This middleware use async function, but code is sync. Is this required to use async function everywhere in koa or there is specific case for it?

Upvotes: 3

Views: 637

Answers (1)

piercus
piercus

Reputation: 1256

Short answer :

You can use sync function as well, it will work perfectly.

Long answer :

Promise vs async

Async function can be replaced by synchronous functions returning Promise into a sync function (see http://2ality.com/2016/10/async-function-tips.html for more info)

Koa compose

Koa is using koa-compose to handle middlewares.

If you check compose function in https://github.com/koajs/compose/blob/master/index.js

Code is

 return Promise.resolve(fn(context, function next () {
  return dispatch(i + 1);
 }))

Your middleware function fn is then bound into Promise.resolve which means that the output will be considered as a Promise even if you return non-Promise.

Sync Promise

It's not documented anywhere and would suggest you to avoid using undocumented patterns and I would do :

 app.use(function(context){
   // ...
   return Promise.resolve();
 })

As a sync design compatible with async.

Upvotes: 4

Related Questions