简体   繁体   中英

Function in node.js

In my node application i am using function.But i am getting the result of that function:

My code:

var connection = mysql.createConnection({
  host     : 'localhost',  
  user     : 'xxxx',
  password : 'xxxxx',
  database : 'xxxxxxx',
  debug : true,
})
connection.connect(function(err) {
    if ( !err ) {
        console.log("Connected to MySQL");
    } else if ( err ) {
        console.log(err);
    }
});

 if(level5 == undefined)
{
   var result1=querylevel5();
   console.log("vvvvvvvvv="+result1)
   res.writeHead(200, { 'Content-Type': 'application/json'});
   res.end(JSON.stringify(result1,null,"\n"));
}

My function:

    function querylevel5()
    {
      var result;    
      connection.query("select * from levels ", function(err, row1, fields) {
        result= row1;
        /*res.writeHead(200, { 'Content-Type': 'application/json'});
        res.end(JSON.stringify(row1,null,"\n"));*/
      });
      return result;
    }

I want to get the row1 result ,in my calling function..But its printing "undefined"..I am new to this node.js..So please help me to solve this..Thanks in advance..

Most likely the problem is that the function querylevel5 returns immediately before result . You have to do like most any other node.js framework does, like for example the connection.query function, namely use callbacks:

if(level5 == undefined) {
    querylevel5(function(result) {
        console.log("vvvvvvvvv="+result)
        res.writeHead(200, { 'Content-Type': 'application/json'});
        res.end(JSON.stringify(result,null,"\n"));
    });
}

And

function querylevel5(callback) {
    connection.query("select * from levels ", function(err, row1, fields) {
        callback(row1);
    });
}

问题是结果是在回调中传递的(即异步),但是您同步调用该方法并打印结果 - 因此在您尝试打印时实际上并未返回结果。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM