node.js - 在 Nodejs 项目中处理 Controller 发送响应的更好方法是什么?

标签 node.js asynchronous callback

rooms.js -> 房间端点的 Controller 类

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 对象的原因是因为在 Controller 中执行 res.status 和 res.send 会出现问题,因为数据库调用是异步的。建议一些更好的做法来处理此类情况。

最佳答案

你是对的。您不应传递 res 对象。如果函数可以从多个地方退出,那么这将是一场调试噩梦。最好是后续函数返回值并且 Controller 响应状态。

您可以简单地创建一个回调方法,异步数据库查询完成后将调用该方法。像这样的事情

router.get('/:roomid/fight/verify', function(req, res) {
      const callback = (status, message) => {
        res.status = status
        res.send(message);
      }
      roomModel.authenticateUserForFight(req.params.roomid, req.query.otp, callback);
    });

主函数可以直接调用这个函数

//authenticate user based on otp provided on client side
exports.authenticateUserForFight = function(roomid, otp, callback) {
  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");
        callback(200, 'user authorized');
      } else {
        console.log("User is unauthorised");
        callback(401, 'user not authorized');

      }
    }
  });
}

关于node.js - 在 Nodejs 项目中处理 Controller 发送响应的更好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45532462/

相关文章:

node.js - 使用 Amazon Cognito 将用户添加到用户池

javascript - 服务器测试中如何处理setInterval

python - 加快多个 CSV 文件的加载速度

java - 为给定值定义回调函数

javascript - Node.js:为 HTTP 代理选择正确的架构,以将许多文件下载给每个用户并将结果作为存档返回

javascript - 如何访问 Mac native 对话框

node.js - 在一个注册表中管理同一个库的 2 个 npm 库版本?

c# - .NET 异步流读/写

javascript - Dart JSONP 回调错误

c# - 具有返回值的 WCF 服务器到客户端回调方法