Node.js:如何将一个查询的输出用于另一个查询的输入

时间:2016-08-23 13:16:23

标签: 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 个答案:

答案 0 :(得分:1)

NodeJs数据库查询是异步的,因此您必须将您的console.log放在回调中,或者使用promises执行。

试一试:

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