【问题标题】:NodeJs - Pass values through condition statement to a callback and get value backNodeJs - 通过条件语句将值传递给回调并取回值
【发布时间】:2017-12-11 17:03:39
【问题描述】:

在我的路由文件中,我有一个条件,即外部函数检查两个值是否相等,obj.id === getId 并根据truefalse 呈现视图或阻止用户。

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

路线文件

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
            }
        }
    })
})

全局函数文件

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) 

}

【问题讨论】:

    标签: javascript node.js express callback


    【解决方案1】:

    您需要传递另一个回调。 对于您的回调实现,它可能应该如下所示:

    // 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 放在callback(null, uid === id) 中?
    • 在您当前的实现中,您不必这样做。我提供了一个节点式回调的版本(也许我不应该这样做)。在节点中,大多数回调都有这样的签名function cb(err, data)。在这种情况下,您必须将null 传递给error。但你不必这样做。很抱歉造成混乱。
    猜你喜欢
    • 2017-01-26
    • 1970-01-01
    • 2019-01-09
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多