• Home
  • About
    • lahuman photo

      lahuman

      열심히 사는 아저씨

    • Learn More
    • Facebook
    • LinkedIn
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

Async Await을 이용하여 처리시 catch를 처리하지 않아 response 무한 대기 현상 해결 방법

03 Aug 2019

Reading time ~1 minute

Async Await을 이용하여 처리시 catch를 처리하지 않아 response 무한 대기 현상

개인적으로 Promise, callback 보다는 async await를 많이 이용한다.

const getSomething = asycn (req, res, next) => {

    const something = await callPromiseObject();

    res.json(something);
}

이와 같이 처리시 기본적으로는 큰 문제가 없지만, callPromiseObject() 를 실행하다 오류가 발생하면 response를 전송하지 못하여 무한 대기 하는 오류가 발생한다.

해결하는 방법은 몇가지가 있는데, 그중 하나는

const getSomething = asycn (req, res, next) => {
    try{
        const something = await callPromiseObject();

        res.json(something);
    }catch(e){
        next(e);
    }
}

이와 같이 try, catch를 이용하는 것이다. 개인적으로 동일한 코드가 계속 반복되어 좋아하는 스타일은 아니다.

또 다른 방법은 Promise를 이용하거나 callback을 이용하는 방식이다.

const asyncHandler = require('express-async-handler')
 
express.get('/', asyncHandler(async (req, res, next) => {
    const bar = await foo.findAll();
    res.send(bar)
}))

이런 방식으로 처리 하는 것인데, 미들웨어 코드를 보면 간단하다.

const asyncUtil = fn =>
function asyncUtilWrap(...args) {
  const fnReturn = fn(...args)
  const next = args[args.length-1]
  return Promise.resolve(fnReturn).catch(next)
}

module.exports = asyncUtil

개인적으로는 미들웨어를 사용하는 방식으로 좀더 쉬운듯 하여 찾아보니 다음과 같은 모듈도 있었다.

var express = require('express')
var wrap = require('async-middleware').wrap
 
var app = express()
 
app.use(wrap(function (req, res) {
  return Promise.reject(new Error('boom!'))
}))

참고자료

  • express-async-handler
  • async-middleware


nodeasync Share Tweet +1