【发布时间】:2018-01-13 21:46:04
【问题描述】:
rooms.js -> 房间端点的控制器类
router.get('/:roomid/fight/verify', function(req, res) {
roomModel.authenticateUserForFight(req.params.roomid, req.query.otp, res);
});
roomModel -> 房间的模型类
//authenticate user based on otp provided on client side
exports.authenticateUserForFight = function(roomid, otp, res) {
db.query('select * from room where roomid=?', [roomid], function(error, rows) {
if (rows.length == 0) {
console.log("otp does not exist in db for room:" + roomid);
} else if (rows.length == 1) {
var otpInDb = rows[0].otp.toString();
if (otp == otpInDb) {
console.log("User is authorised");
res.status(200);
res.send("User is authorised");
} else {
console.log("User is unauthorised");
res.status(401);
res.send("User not authorised");
}
}
});
}
这段代码工作正常,但是有没有更好的方法来向客户端发送响应,而不是将 res 对象传递给模型类并在那里设置状态和响应消息?我传递 res 对象的原因是因为在控制器中执行 res.status 和 res.send 会产生问题,因为 db 调用是异步的。建议一些更好的做法来处理这些情况。
【问题讨论】:
标签: node.js asynchronous callback