[英]Convert the syntax to async-await
I would like to convert the syntax to async-await.我想将语法转换为 async-await。 is it worthy?值得吗? how can I do it?我该怎么做?
// ---- 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);
});
};
I tried to use async/await methods examples to rewrite the code but it threw errors so I wouldn't share the thing that does not work but I found this helpful/我尝试使用 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)
}
})
Next step was to implement it in a Router, Service, DAO model but then it didn't work...下一步是在路由器、服务、DAO 模型中实现它,但它不起作用......
This is to show how to use async/await in express routes.这是为了展示如何在快速路由中使用 async/await。
router.get('/user', middlewareJwt.jwtHandler, async function (req, res) {
try{
var result = await UserService.get(req.userId);
res(result);
}catch(error){
res(error);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.