21.3.2.1 next 함수는 Promise를 반환

    next 함수를 호출하면 Promise를 반환합니다. 이는 Koa가 Express와 차별화되는 부분입니다. next 함수가 반환하는 Promise는 다음에 처리해야 할 미들웨어가 끝나야 완료됩니다. 다음과 같이 next 함수 호출 이후에 then을 사용하여 Promise가 끝난 다음 콘솔에 END를 기록하도록 수정해 보세요.

    index.js

    const Koa = require('koa');
    
    const app = new Koa();
    
    app.use((ctx, next) => {
      console.log(ctx.url);
      console.log(1);
      if (ctx.query.authorized != = '1') {
        ctx.status = 401; // Unauthorized
        return;
      }
      next().then(() => {
        console.log('END');
      });
    });
    
    app.use((ctx, next) => {
      console.log(2);
      next();
    });
    
    app.use(ctx => {
      ctx.body = 'hello world';
    });
    
    app.listen(4000, () => {
      console.log('Listening to port 4000');
    });

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.