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

时间:2017-12-11 17:03:40

标签: javascript node.js express callback

在我的路径文件中,我有一个条件,其中外部函数检查两个值是否相等,import Foundation struct SomeError: Error { let code: Int? let message: String? let errorDescription: String? var allValuesSet: Bool { for aChild in Mirror(reflecting: self).children { if case Optional<Any>.some(_) = aChild.value { continue } else { return false } } return true } } let errorTest = SomeError(code: nil, message: "failed", errorDescription: nil) let errorTest2 = SomeError(code: -1, message: "failed", errorDescription: "missing information") print("is valid: \(errorTest.allValuesSet)") //is valid: false print("is valid: \(errorTest2.allValuesSet)") //is valid: true 并相应地obj.id === getIdtrue呈现视图或阻止用户

我尝试用作回调的函数false,它获取传递给它的值,但我无法将checkUsertrue的结果返回给我路线档案。

  

路线档案

false
  

全局函数文件

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

1 个答案:

答案 0 :(得分: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);