我有一个使用node-oracledb连接到Oracle的Node / Express.js应用程序。
我正在尝试向我的视图返回多个查询,但是我在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
答案 0 :(得分:2)
您可以使用Bluebird或async promises库来执行此操作。
使用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;
答案 1 :(得分:1)
如果查询执行的顺序对您无关紧要,您可以使用Promise.all()
,如下所示:
Promise.all([
connection.execute(query1),
connection.execute(query2),
...
])
.then((results) => {
// => results is an array containing the results from each query
});