21.3.2.2 async/await 사용하기

    Koa는 async/await를 정식으로 지원하기 때문에 해당 문법을 아주 편하게 사용할 수 있습니다.

    노트 서버 사이드 렌더링을 할 때 사용했던 Express도 async/await 문법을 사용할 수 있지만, 오류를 처리하는 부분이 제대로 작동하지 않을 수 있습니다. 백엔드 개발을 하면서 예상치 못한 에러를 제대로 잡아내려면 express-async-errors라는 라이브러리를 따로 사용해야 합니다.

     

    기존 코드를 async/await를 사용하는 형태로 한번 수정해 봅시다.

    index.js

    const Koa = require('koa');
    
    const app = new Koa();
    
    app.use(async (ctx, next) => {
      console.log(ctx.url);
      console.log(1);
      if (ctx.query.authorized != = '1') {
        ctx.status = 401; // Unauthorized
        return;
      }
      await next();
      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');
    });

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