我想将语法转换为async-await。值得吗?我该怎么办?
// ---- UserRoutes ----
router.get('/user', middlewareJwt.jwtHandler, function (req, res) {
UserService.get(req.userId,
(user) => successCbk(res, 200, { user: user }),
(err) => errorCbk(res, 400, err),
);
});
// ---- UserService ----
const get = (userId, successCbk, errorCbk) => {
return UserDAO.get(userId, successCbk, errorCbk);
};
// ---- userDAO ----
const get = (userId, successCbk, errorCbk) => {
User.findOne({ "_id": userId }, function (err, user) {
if(err) return errorCbk(err);
user.password = "***";
return successCbk(user);
});
};
我尝试使用async / await方法示例重写代码,但是它引发了错误,所以我不会分享不起作用的内容,但是我发现这很有帮助/
router.get('/user/:id', async (req, res, next) => {
try {
const user = await getUserFromDb({ id: req.params.id })
res.json(user);
} catch (e) {
//this will eventually be handled by your error handling middleware
next(e)
}
})
下一步是在路由器,服务,DAO模型中实现它,但后来却不起作用...
答案 0 :(得分:0)
这是显示如何在快速路由中使用异步/等待。
router.get('/user', middlewareJwt.jwtHandler, async function (req, res) {
try{
var result = await UserService.get(req.userId);
res(result);
}catch(error){
res(error);
}
});