在node.js中返回null值?

我在nodejs是新的。 这是我在nodejs文件中的代码。 我想从nodejs发送数据到其他javascript使用json.stringify ,但我的问题是我得到值… —————-编辑——- —————-

我的代码是

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

如何解决这个问题?

您将需要使用callback,直接返回数据将只返回null因为在所有数据准备就绪后,会稍后调用end事件处理程序。 尝试像这样:

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

问题是nodejs是asynchronous的。 它会执行你的res.write(JSON.stringify(data)); 在你的函数被调用之前。 你有两个select:一个避免callback:

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

另一个在callback函数中有这样的响应:

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