2016-12-27 98 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 
});