Search code examples
javascriptnode.jspromiseasync-awaitkoa

In Koa, what's the difference between await next(), return await next(), return next(), and next() in middleware?


The documentation outlines the use-case for using 'await next()' in middleware, causing the middleware to pause and trigger the next middleware downstream until all middlewares are done executing at which point the upstream cascade will begin and the middlewares will complete execution. And if a user wants to cut the cascade short then writing 'return' alone will cut the cascade all together.

What I don't understand is what happens if the user returns one of the following:

const exampleMiddleware1 = async (ctx, next) => {
  return await next();

  console.log('Doing something');
};

const exampleMiddleware2 = async (ctx, next) => {
  next();

  console.log('Doing something');
};

const exampleMiddleware3 = async (ctx, next) => {
  return next();

  console.log('Doing something');
};

In the first example, I think it will pause, trigger the next middleware, but will not finish the execution on the upward cascade.

In the second example, I think the next middleware will be triggered along with the console.log, I don't think it will trigger on the upward, maybe?

In the third example, I think the next middleware will be triggered but it will not trigger the console log on the upward cascade, the same as the first example.

Is my thinking correct? I'm writing a koa app and would like to learn more about its limits and I find this one area I don't understand clearly.


Solution

  • exampleMiddleware1 and exampleMiddleware3 is the same (no need to return await unless you want to catch error before return)

    • your console.log will never be called

    exampleMiddleware2

    1. If next middleware return promise

      • your console.log will call without waiting for next middleware fufiled
    2. If next middleware not return promise

      • It will finish next middleware then console.log