2017-11-16 6 views
0

원래 getAllUsers 메서드에서 쿼리를 위해 try...catch을 가졌지 만 제거 할 수 없었다. 비동기 함수가 약속을 반환하므로 코드가 구조화 된 방식을 기반으로 실제로 잘되어야합니다. 그렇지 않으면 쿼리에서 try...catch이 필요하다는 생각에 따라 오류가 발생합니다. 이 구조에서 누락 된 것이 있습니까? async/await, try...catch.then .catch?랩 비동기는 try catch에서 쿼리를 기다린다

let getAllUsers = async() => { 
    let res = await models.users.findAll({ 
     attributes: [ 'firstName', 'lastName' ] 
    }); 
    return res; 
}; 

router.get(`${path}`, (req, res) => { 
    queries.users.getAllUsers() 
     .then(users => { 
     res.status(200).json(users); 
     }) 
     .catch(error => { 
     res.status(500).send(error) 
     }); 
}); 

답변

2

함수에 모든 await를 사용하는 단지 이유가 없다 : 여기

// based upon this 
// http://madole.xyz/error-handling-in-express-with-async-await-routes/ 
// https://github.com/madole/async-error-catcher 

export default function asyncErrorCatcher(fn) { 
    if (!(fn instanceof Function)) { 
     throw new Error("Must supply a function"); 
    } 

    return (request, response, next) => { 
     const promise = fn(request, response, next); 
     if (!promise.catch) { 
      return; 
     } 
     promise.catch((error) => { 
      console.log(error.message); 
      response.sendStatus(500); 
     }); 

    }; 
} 

이 사용입니다 : 여기

는 기능입니다. 대신이의 :

let getAllUsers = async() => { 
    let res = await models.users.findAll({ 
     attributes: [ 'firstName', 'lastName' ] 
    }); 
    return res; 
}; 

그냥이 될 수 있습니다 : 당신은 그냥 직접 약속을 반환

let getAllUsers =() => { 
    return models.users.findAll({ 
     attributes: [ 'firstName', 'lastName' ] 
    }); 
}; 

와 발신자는 이미 있던 동일하게 약속을 사용합니다. getAllUsers() 함수 내에서 결과를 사용하거나 다른 것으로 조정하지 않으므로 await을 사용할 이유가 없습니다. 그리고, await을 사용하지 않기 때문에, 함수가 async으로 선언 될 이유가 없습니다.


당신이 await을 사용하고자하는 경우에는이 같은 getAllUsers()의 호출을 위해 그것을 사용할 수 있습니다 거부 약속을 잡기 위해 당신이 시도 사용해야 할 것입니다 여기

router.get(`${path}`, async (req, res) => { 
    try { 
     let users = await queries.users.getAllUsers(); 
     res.status(200).json(users); 
    } catch(error => { 
     res.status(500).json(error); 
    } 
}); 

그리고,/캐치 . 개인적으로, 이것이 원래 당신이 .then().catch()을 가지고 있었던 것보다 특히 좋은 것을 보지 못합니다. 그래서 이것과 같은 간단한 상황 (다른 약속과의 조정이나 직렬화가없는 상황)은 개인적인 취향에 상관없이 .then().catch() 또는 awaittry/catch을 사용하십시오.

0

가장 좋은 방법은 미들웨어를 사용하는 것입니다.

router.get("/getSettings/", asyncErrorCatcher(async (request: Request, response: Response) => { 
    const settings = await database.getSettings(); 
    response.json(settings); 
})); 
2

당신은 그 자체 getAllUsers에서 그것을 사용하는 것보다 getAllUsers를 대신 호출하는 코드로 async/await를 사용합니다 :

const getAllUsers =() => { 
    return models.users.findAll({ 
     attributes: [ 'firstName', 'lastName' ] 
    }); 
}; 

router.get(`${path}`, async (req, res) => { 
    try { 
     const users = await queries.users.getAllUsers(); 
     res.status(200).json(users); 
    } catch (error) { 
     res.status(500).send(error) 
    } 
});