2016-12-27 59 views
0

我有一个使用node-oracledb连接到Oracle的Node/Express.js应用程序。如何使用Node承诺从Oracle返回多个结果集

我试图将多个查询返回到我的视图,但是我在Node-Oracle项目中找到的所有示例都是针对单个查询的。 https://github.com/oracle/node-oracledb/tree/master/examples

网上有各种各样的信息,但我找不到与这种确切情况有关的任何事情,我可以用一个例子来工作。我发现最近的是这个问题:oracledb chaining sql call using promises被带到Github,并没有真正回答。

工作代码,我至今是:

var express = require('express'); 
var router = express.Router(); 
var oracledb = require('oracledb'); 

/* GET home page. */ 
router.get('/', function(req, res, next) { 

    oracledb.getConnection() 
    .then(function(connection) { 
    return connection.execute(
     "SELECT note_id, name " + 
     "FROM notes " + 
     "WHERE note_id = :did", 
     [1234] 
    ) 
    .then(function(result) { 
     res.render('index', { title: 'Express', table: result }); 
     return connection.close(); 
    }).catch(function(err) { 
     console.log(err.message); 
     return connection.close(); 
    }) 
    }) 
    .catch(function(err) { console.log(err.message); }) 

}); 

module.exports = router; 

我如何可以与多个查询这项工作,并将结果传递给模板?

res.render('index', { title: 'Express', table: result, table2: result2 }); 

编辑:我的例子是基于这样的:https://github.com/oracle/node-oracledb/blob/master/examples/promises.js

回答

2

你可以使用Bluebirdasync承诺库来做到这一点。

使用Bluebird您可以修改代码,如下图所示:

router.get('/', function(req, res, next) { 

    var getConnectionP = oracledb.getConnection(); 

    getConnectionP.then(function(connection) { 

//Defining each query as a separate promise i.e query1P and query2P as both of them returns a promise 

     var query1P = connection.execute(
      "SELECT note_id, name " + 
      "FROM notes " + 
      "WHERE note_id = :did", 
      [1234] 
     ); 

     var query2P = connection.execute(
      "SELECT note_id, name " + 
      "FROM notes " + 
      "WHERE note_id = :did", 
      [5678] 
     ); 

//Promise.join as the name says, gets resolved only when both the promises passed to it gets resolved and their results are available in the "spread" function callback as shown below : 

     Promise.join(query1P, query2P).spread(function (result, result2){ 
     res.render('index', { title: 'Express', table: result, table2: result2 }); 
     return connection.close(); 
     }) 
     .catch(function (err){ 
     console.log(err.message); 
     return connection.close(); 
     }); 
    }); 
}); 

module.exports = router; 
+0

与蓝鸟的伟大工程。 Promise.all()方法也起作用,但每次都需要处理一秒。我不确定它是否以某种方式重建连接(不应该像它被合并)。然而这个解决方案非常快。 – username

+0

很酷。很高兴我能帮上忙 :) – superUser

0

如果查询的执行顺序无关紧要的话,你可以使用Promise.all()像这样:

Promise.all([ 
    connection.execute(query1), 
    connection.execute(query2), 
    ... 
]) 
.then((results) => { 
    // => results is an array containing the results from each query 
});