Search code examples
node.jsasync-awaitkoaecmascript-2017

About async/await in koa2


I use async/await in koa2 like following

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

app.use(async (ctx, next) => {
  await next()
  console.log("1------>"+Date.now())
});

app.use(async (ctx, next) => {
  await next()
  console.log("2------>"+Date.now())
});

app.use(async (ctx, next) => {
  await next()
  console.log("3------>"+Date.now())
});

app.use(async (ctx, next) => {
  await next()
  console.log("4------>"+Date.now())
});

app.listen(3000);

Run this code, I will get the log like this

4------>1526575713792
3------>1526575713794
2------>1526575713795
1------>1526575713795

And here are my questions

  1. What's the next in app.use(async (ctx, next), is it a function?

  2. await next() in each app.use function means wait, please run the next app.use first, if has no next app.use, ignore it, and run the code in last app.use fuction, am I right?

  3. If I change the first one app.use to app.use(async (ctx) => { console.log("1------>"+Date.now())});, and run it, the result has only one records 1------>1526576945380. I thought the second app.use function will continue running, and I will get the result like this

    1------>1526576945360

    4------>1526575761869

    3------>1526575761869

    2------>1526575761869

So, can anyone help me? and explain for me? Many thanks.


Solution

    1. yes next is a function, console.log(typeof next) would have shown you that.
    2. Yes, calling next will instruct koa to execute the next middleware that was registered using e.g. use, and returns a Promise that is resolve as soon as the next middlewae is resolve, with await in front of that next your code will wait there until that Promise is resolved.
    3. why do you expect that the next middlewares that was registered with use are called? You don't call next so you terminate at in this middleware. await is a js functionality to wait for a Promise to be resolved. next is the koa functionality to execute the next middleware.