Javascript NodeJs-通过条件语句将值传递给回调函数并返回值
在我的路由文件中,我有一个条件,外部函数检查两个值是否相等,Javascript NodeJs-通过条件语句将值传递给回调函数并返回值,javascript,node.js,express,callback,Javascript,Node.js,Express,Callback,在我的路由文件中,我有一个条件,外部函数检查两个值是否相等,obj.id===getId,并相应地根据true或false呈现视图或阻止用户 我尝试将函数checkUser用作回调函数,它获取传递给它的值,但我无法将true或false的结果返回到路由文件 路由文件 全局函数文件 您需要传递另一个回调。 对于回调实现,它可能如下所示: // here is the checking point that will use the callback fcs.checkUser(obj.id,
obj.id===getId
,并相应地根据true
或false
呈现视图或阻止用户
我尝试将函数checkUser
用作回调函数,它获取传递给它的值,但我无法将true
或false
的结果返回到路由文件
路由文件
全局函数文件
您需要传递另一个回调。 对于回调实现,它可能如下所示:
// here is the checking point that will use the callback
fcs.checkUser(obj.id, getId, function(userValid){
if(userValid){
res.render('showuser');
} else {
// some code
}
));
节点样式回调:
// here is the checking point that will use the callback
fcs.checkUser(obj.id, getId, function(err, userValid){
if(userValid){
res.render('showuser');
} else {
// some code
}
));
您的
checkUser
应该这样调用回调:callback(null,uid==id)
为什么我必须将null
放入回调(null,uid==id)
?在您当前的实现中,您不必这样做。我提供了一个版本的节点样式回调(也许我不应该这样做)。在节点中,大多数回调都有这样的签名函数cb(err,data)
。在这种情况下,您必须为错误传递null
。但你不必这么做。抱歉搞混了。
// here is the checking point that will use the callback
fcs.checkUser(obj.id, getId, function(userValid){
if(userValid){
res.render('showuser');
} else {
// some code
}
));
// here is the checking point that will use the callback
fcs.checkUser(obj.id, getId, function(err, userValid){
if(userValid){
res.render('showuser');
} else {
// some code
}
));