我在后端应用程序中使用node。我编写了一个方法,它从express request对象获得一些输入。该方法通过res.write(.)执行一些检查,并将消息写入响应对象。在所有检查结束时,我都调用了res.end();到目前为止还不错。我的一些检查需要mongodb访问,因此我必须使用回调。下面是一些代码:
app.post("/addUser", function (req, res) {
expdb.unique({ "email": req.body.email }, function (isUnique) {
if (!isUnique) {
res.write("email error");
}
})
expdb.unique({ "_id": req.body.user }, function (isUnique) {
if (!isUnique) {
res.write("user error");
}
})
/* -- below here everything works fine -- */
if (req.body.user.length < 3 || req.body.user.length > 20) {
res.write("username to short ...or to long");
}
/* -- ... more working code -- */
res.end();
});
前两个响应被完全忽略。我很确定这里正在发生一些古怪的回调魔法,但我不知道如何做好。我尝试了下面这样的方法,以确保回调知道响应对象,但它也失败了:
expdb.unique({"_id": req.body.user}, function(result, respond) {
if(!result) {
respond.write("user error")
}
}, res)
希望有人能帮我这个忙。
谢谢-Dirk
发布于 2016-11-18 20:53:17
多亏了卡尔曼,我终于把它做对了。下面是正在寻找它的人的工作代码:
app.post("/addUser", function (req, res) {
expdb.unique({ "email": req.body.email }, function (uniqueEmail) {
if (!uniqueEmail) {
res.write("Email in use\n");
}
expdb.unique({ "_id": req.body.user }, function (uniqueUser) {
if (!uniqueUser) {
res.write("Username in use\n");
}
if (req.body.user.length < 3 || req.body.user.length > 20) {
res.write("username to short ...or to long\n");
}
/* -- other validations --*/
res.end();
});
});
});
发布于 2016-11-18 20:19:35
正如评论中所提到的,以下内容应该有效
var theEnd = function(response){
if (req.body.user.length < 3 || req.body.user.length > 20) {
res.write("username to short ...or to long");
}
/* -- ... more working code -- */
res.end();
};
app.post("/addUser", function (req, res) {
expdb.unique({ "email": req.body.email }, function (isUnique) {
if (!isUnique) {
res.write("email error");
}
theEnd(res);
})
expdb.unique({ "_id": req.body.user }, function (isUnique) {
if (!isUnique) {
res.write("user error");
}
theEnd(res);
})
https://stackoverflow.com/questions/40681290
复制相似问题