ltv*_*vie 1 javascript node.js
我是新人nodejs.这是我的nodejs文件代码.我想将数据发送nodejs到其他javascript用途json.stringify,但我的问题是我得到空值... ---------------- EDIT ------------ -----------
我的代码是
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
}
});
}
Run Code Online (Sandbox Code Playgroud)
如何解决这个问题?
您将需要使用回调,直接返回数据将返回,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);
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6543 次 |
| 最近记录: |