查询 SQL NodeJS + 乏味:request.on('done', cb) 未被调用和嵌套查询



我正在尝试发出请求,将返回的数据添加到请求的"row"事件中的cb上的对象中,然后在"done"cb中执行某些操作。很简单;但是,"完成"事件显然没有被触发。这是我当前的代码:

var connection = new Connection(config);
var executeTest = function (connection) {
 var result = [];
 var statement = "select val1, val2 from table;"
 var request = new Request(statement, function (err, rowCount) {
   if (err) {
    console.log(err);
   }
   console.log(rowCount);
   connection.close();
 });
 request.on('row', function(columns) {
  var thisRow = {};
  columns.forEach(function(column) {
    thisRow[column.metadata.colName] = column.value;
    result.push(thisRow);     
  });
  console.log(result); //not empty
  //tried making request2 here, no dice
  //tried making a second connection here, no dice
  //got error:
  //'requests can only be made in the LoggedIn state, 
  //not the SentClientRequest state' :(
 })  
 request.on('done', function (rC, more, row) { //never called
   console.log(rC, more, row);
   //other things to do
 })
 connection.execSql(request);
}
function test () {
 var connection = new Connection(configure);
 connection.on('connect', function(err) {
   if (err) {console.log(err);}
   console.log("Connected");
   executeTest(connection);
 })
}
test();
console.log(result); // []
//make second request using values from result

此外,如果有人可以解释如何将查询的结果用作另一个查询中的参数,那就太好了。调用测试后,obv 结果为空,但是当它在request.on('row', cb)中不为空时,我无法使用当前的thisRow obj在该cb中发出第二个请求。 我需要使用事务吗?如果是这样,有人可以举个例子来说明如何使用繁琐的事务进行嵌套查询,其中第一个查询的结果作为参数提供给第二个查询?谢谢。

要发出第二个请求,您需要将回调传递到包装繁琐请求的函数中。为了简单起见,我对代码进行了一些简化:

var statement = "select val1, val2 from table";
function executeTest(connection, callback) {
    var results = [];
    var request = new Request(statement, function(error) {
        if (error) {
            return callback(error);
        }
        // pass the results array on through the callback
        callback(null, results);
    });
    request.on("row", function(rowObject) {
        // populate the results array
        results.push(rowObject);
    });
    connection.execSql(request);
}
function test() {
    /*
    create connection code
     */
    executeTest(connection, function(error, results) {
        // here is the results array from the first query
        console.log(results);
    });
}
test();

关键点是请求是异步的,因此必须将结果传递给回调。这意味着如果你想在其他地方使用代码,你需要将回调参数传递给executeTest

最新更新