在我的路由文件中,我有一个条件,外部函数检查两个值是否相等,obj.id === getId
并相应地为true
或false
它会渲染 View 或阻止用户。
我尝试将函数 checkUser
用作回调,它获取传递给它的值,但我无法取回 true
或 false
到我的路线文件。
Route file
const express = require('express')
const router = express.Router()
const fcs = require('../routes/functions') //Global functions file
router.get('/:id', fcs.isLoggedIn, function(req, res, next) {
getId = req.params.id
db.con.query('SELECT * FROM employees where id=?', getId, function(err, results, callback) {
if (err) {
//some code
return
} else {
try {
//some code for getting results to obj{}
// here is the checking point that will use the callback
if (fcs.checkUser(obj.id, getId)) {
res.render('showuser')
} else {
//some code
}
} catch (err) {
//some code
}
}
})
})
Global Functions file
const express = require('express')
const router = express.Router()
module.exports.checkUser = function checkUser(uid, id, callback) {
// it gets true or false with no problem
console.log(uid === id)
// Need to send the output of true or false back to the condition checker (route file)
callback(uid === id)
}
最佳答案
您需要传递另一个回调。 对于您的回调实现,它可能应该如下所示:
// 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
}
));
Node 式回调:
// 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);
关于javascript - NodeJs - 通过条件语句将值传递给回调并获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47757804/