javascript - NodeJs - 通过条件语句将值传递给回调并获取值

标签 javascript node.js express callback

在我的路由文件中,我有一个条件,外部函数检查两个值是否相等,obj.id === getId并相应地为truefalse 它会渲染 View 或阻止用户。

我尝试将函数 checkUser 用作回调,它获取传递给它的值,但我无法取回 truefalse 到我的路线文件。

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/

相关文章:

javascript - 在 JavaScript 中包含 JSF 表达式语言

javascript - 使用 webpack ou npm 在多个包中拆分 javascript Javascript 项目

javascript - NPM - 脚本 - 它们如何工作?

javascript - Expressjs语言库

javascript - 如何从来自同一域的 iframe 访问 JSON?

Javascript - 将用户输入值与随机生成的值进行比较

javascript - 表单中的运输详细信息验证

arrays - 更新嵌套在 mongodb 对象数组中的字符串数组

javascript - 如何同时调用两个不同的 REST api 端点并在应用程序的一个端点上显示来自这两个端点的数据?

node.js - 处理 Express JS 路由中的空参数