我有一个使用 node-oracledb 连接到 Oracle 的 Node/Express.js 应用程序。
我试图将多个查询返回到我的 View ,但是我在 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
最佳答案
您可以使用Bluebird或async图书馆 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;
关于node.js - 如何使用 Node Promise 从 Oracle 返回多个结果集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41350347/