我使用Node.js和Expressjs作为服务器端编码,MongoDB作为后端。我对所有这些技术都很陌生。 我需要根据请求执行一系列操作。有没有更好的方法来处理Node.js/Expressjs中的嵌套回调?
例如,在用户管理
- 检查用户已经注册
- 如果注册重发激活邮件
- 如果没有登记,然后从另一个表将保持IDS对用户获取用户标识,资产等。[我知道MongoDB提供独特的_id;但我需要一个唯一的整数ID为userId]
- 创建用户
- 发送成功或失败响应。
要实现这一点,我写了下面的代码:
exports.register = function(req,res,state,_this,callback) {
switch(state) {
case 1: //check user already registered or not
_this.checkUser(req, res, (state + 1), _this, _this.register, callback);
break;
case 2: //Already registered user so resend the activation email
_this.resendEmail(req, res, 200, _this, _this.register, callback);
break;
case 3: //not registered user so get the userId from another table that will maintain the ids for user,assets etc
_this.getSysIds(req, res, (state + 2), _this, _this.register, callback);
break;
case 4: //create the entry in user table
_this.createUser(req, res, (state + 1), _this, _this.register, callback);
break;
case 200: //Create Success Response
callback(true);
break;
case 101://Error
callback(false);
break;
default:
callback(false);
break;
}
};
校验用户代码是这样的
exports.checkUser = function(req,res,state,_this,next,callback) {
//check user already registered or not
if(user) {//Already registered user so resend the activation email
next(req,res,state,_this,callback);
}
else {//not registered user so get the userId
next(req,res,(state + 1),_this,callback);
}
}
,类似地等功能。
寄存器函数的第一次调用将从app.get做的
user.register(req,res,1,this,function(status) {
//do somthing
});
有没有什么更好的方法来做到这一点?我面临的问题是基于一些条件,我必须遵循一系列的行动。我可以将所有这些写入嵌套的回调结构中,但在这种情况下,我无法重用我的代码。
一个问题,我的老板告诉我的是,在代码中我打电话的功能寄存器,并把它放在回调的堆栈
状态1:chekuser
状态3:getIds
状态4:创建用户
最后在状态200,这里我只是退出堆栈?它可能会导致堆栈溢出!
有没有更好的方法来处理Node.js/Expressjs中的回调?
注意:以上是一个示例code.I有这样的许多不同的情况。
性能怎么样?这是一种很好的编码方式吗? – Damodaran
从我的理解来看,这是一种非常高性能的编码方式,因为node.js是非阻塞的。函数A在函数B执行完成时执行。如果函数A是需要2秒才能完成的数据库调用,那么服务器只会继续执行其他操作,直到A完成。似乎是一种很好的编码方式。 – hobberwickey