简体   繁体   English

在node.js中返回空值?

[英]return null value in node.js?

I am new in nodejs . 我是nodejs Here is my code in nodejs file. 这是我在nodejs文件中的代码。 i want to send data from nodejs to other javascript use json.stringify ,but my problem is i get null value... ----------------EDIT----------------------- 我想将数据从nodejs发送到其他javascript使用json.stringify ,但我的问题是我得到了值... ----------------编辑------- ----------------

my code is 我的代码是

function handler ( req, res ) {
        calldb(dr,ke,function(data){
            console.log(data); //successfully return value from calldb                                      
        });
    //i think my problem bellow...
    res.write( JSON.stringify(data)); //send data to other but it's null value
    res.end('\n');
}

function calldb(Dr,Ke,callback){
    // Doing the database query
    query = connection.query("select id,user from tabel"),
        datachat = []; // this array will contain the result of our db query
    query
    .on('error', function(err) {
        console.log( err );
    })
    .on('result', function( user ) {
        datachat.push( user );
    })
    .on('end',function(){
        if(connectionsArray.length) {
            jsonStringx = JSON.stringify( datachat );
            callback(jsonStringx); //send result query to handler
        }
    });

}

How to fix this problem? 如何解决这个问题?

You will need to use callbacks, returning data directly will just return null because the end event handler is called later when all the data is ready. 您将需要使用回调,直接返回数据将仅返回null因为在所有数据就绪后,将调用end事件处理程序。 Try something like : 尝试类似的东西:

function handler ( req, res ) {
    calldb(dr, ke, function(data){
       console.log(data);
       res.write( JSON.stringify(data)); 
       res.end('\n');
    });
}

function calldb(Dr,Ke, callback) { 

    var query = connection.query('SELECT id,userfrom tabel'),
        datachat= []; // this array will contain the result of our db query

    query
     .on('error', function(err) {
        console.log( err );
     })
     .on('result', function( user ) {
        datachat.push( user );
     })
     .on('end',function() {
        callback(datachat);
    }); 

}

The problem is that nodejs is asynchronous. 问题在于nodejs是异步的。 It will execute your res.write( JSON.stringify(data)); 它将执行您的res.write(JSON.stringify(data)); before your function will be called. 在您的函数将被调用之前。 You have two options: one to avoid callback: 您有两种选择:一种避免回调:

    .on('end',function(){
      if(connectionsArray.length) {
        jsonStringx = JSON.stringify( datachat );
        res.write( JSON.stringify(data)); 
        res.end('\n');
      }
    }

the other have the response in the callback function like this: 另一个在回调函数中具有如下响应:

function boxold() {
  box(function(data) {
        res.write( JSON.stringify(data)); 
        res.end('\n');
        //console.log(data);
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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