我如何调用此nodejs函数作为JSON对象用于另一个函数

时间:2018-01-19 10:24:28

标签: json node.js

我有一个名为categories的变量,它应该保存从mysql数据库获取值的函数返回的对象 无论何时我想访问此变量以便将其用作JSON对象,我都无法访问以下数据是我的代码

  //this is the variable that is supposed to return a JSON object containing value from mysql
  var categories= function(req,res){
  req.getConnection(function(err,connection){
    if(err){
      console.log('Connection yanze'+err)
    }else{
      connection.query('select * from categories',function(err,results){
        if(err){
          throw err;

        }else{

        return (JSON.stringify(results));

          }
      })
    }
  })
}

app.get('/',function(req,res,next){
  res.render('index',{title:'Voila',category:categories});
 console.log(categories);//whenever i try to print this variable it only prints the name of the variable instead of printing the the content of the object
})

1 个答案:

答案 0 :(得分:0)

对我来说,像这样,你将变量类别定义为一个函数,而不是函数的结果。

尝试这样的事情:

function getCategories(req,res){
  req.getConnection(function(err,connection){
    if(err){
      console.log('Connection yanze'+err)
    }else{
      connection.query('select * from categories',function(err,results){
        if(err){
          throw err;

        }else{

        return (JSON.stringify(results));

          }
      })
    }
  })
}

var categories = getCategories(req1, res1);