2016-08-23 73 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']); 
     }); 
    }); 
}); 
相关问题