2016-08-23 78 views
0

我是新來的node.js的投入,我想查詢到另一個查詢的輸入輸出,請幫助的Node.js:如何使用一個查詢的輸出到另一個查詢

pool.getConnection(function(err, connection) { 
    connection.query("select * from tbl_chat", function(err, rows) { 
     console.log(rows[0]['from_id']); 
     var fromid = rows[0]['from_id']; 
    }); 
    console.log(fromid);//throws ReferenceError: fromid is not defined 
    console.log(rows[0]['from_id']);// throws ReferenceError: rows is not defined 

    //I want to use the fromid in the following query 

    /*connection.query("select * from tbl_chat where from_id=?",[fromid], function(err, rows) { 
     console.log(rows[0]['from_id']); 
    });*/ 
}); 

回答

1

的NodeJS數據庫查詢是異步的,所以你必須把你的console.log放在回調中,或者用promise來做。

試試:

pool.getConnection(function(err, connection) { 
    connection.query("select * from tbl_chat", function(err, rows) { 
     console.log(rows[0]['from_id']); 
     var fromid = rows[0]['from_id']; 
     console.log(fromid); 
     console.log(rows[0]['from_id']); 
     connection.query("select * from tbl_chat where from_id=?",[fromid], function(err, rows) { 
      console.log(rows[0]['from_id']); 
     }); 
    }); 
}); 
相關問題