함수에 모든 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()
또는 await
과 try/catch
을 사용하십시오.