2013-05-04 64 views
1

我是nodejs。這裏是我的代碼nodejs文件。 我想從nodejs發送數據到其他javascript使用json.stringify,但我的問題是我得到null值... ----------------編輯----- ------------------在node.js中返回空值?

我的代碼是

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

} 

如何解決這個問題?

回答

6

您將需要使用回調,直接返回數據將僅返回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); 
    }); 

} 
+0

Thanks..i按照你的代碼,但我得到的錯誤「字符串沒有功能'..如何解決這個問題? – ltvie 2013-05-04 05:18:58

+0

我的問題是修復,但我得到空值時,我發送值在其他功能...看到編輯(我改變我的代碼) – ltvie 2013-05-04 10:04:15

+0

更新了我的答案。 – 2013-05-04 14:10:31

1

問題是nodejs是異步的。它會執行你的res.write(JSON.stringify(data));在你的函數被調用之前。你有兩個選擇:一是避免回調:

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

其他在回調函數這樣的迴應:

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