A callback function is passed as an argument to another function. In order to respect the separation of concerns, how can I rewrite the following example as a callback? I know that the Req,Res part is outsourced to the router.
Userservice.js
function getByUserId(req, res, next) {
let userIDD = req.body.userID;
User.findOne({
userID: userIDD
}, function(err, result) {
if (err) {
console.log("error: " err)
} else {
console.log("Awesome.");
res.send(result)
}
})
}
UserRoute.js
router.post('/publicUser/getByUserID', userService.getByUserId)
CodePudding user response:
I think it is good now but if you want to use callback and use this function as a middleware you can do next(result)
instead of res.send(result)
CodePudding user response:
If you want to declare a callback function directly in your post
method you can use an arrow function:
router.post('/publicUser/getByUserID', (req, res) => {
let userIDD = req.body.userID;
User.findOne({
userID: userIDD
}, function(err, result) {
if (err) {
console.log("error: " err)
return res.send(err);
}
console.log("Awesome.");
res.send(result)
})
})