[英]How to use Node promises to return multiple result sets from Oracle
我有一个使用node-oracledb连接到Oracle的Node / Express.js应用程序。
我试图将多个查询返回到我的视图,但是我在Node-Oracle项目中找到的所有示例都是针对单个查询的。 https://github.com/oracle/node-oracledb/tree/master/examples
网上有各种各样的信息,但是我可以通过一个示例找到与这种确切情况相关的任何信息。 我发现的最接近的问题是:使用Promise的oracledb链接sql调用被带到了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
您可以使用Bluebird或异步 Promise库来做到这一点。
使用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;
如果查询执行的顺序对您而言无关紧要,则可以像下面这样使用Promise.all()
:
Promise.all([
connection.execute(query1),
connection.execute(query2),
...
])
.then((results) => {
// => results is an array containing the results from each query
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.