我是 nodejs
的新手。这是我在 nodejs
文件中的代码。
我想使用 json.stringify
将数据从 nodejs
发送到其他 javascript
,但我的问题是我得到了 null值(value)...
--------------编辑------------------------
我的代码是
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
}
});
}
如何解决这个问题?
最佳答案
您将需要使用回调,直接返回数据只会返回 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);
});
}
关于javascript - 在 node.js 中返回空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16370367/