Dav*_*ega 7 javascript pg-promise
目前我有以下代码来获取两个查询的结果
dbro.many("SELECT geoname_id, country_name FROM paises WHERE locale_code=$1 LIMIT 10",data.lang)
.then(function(countriesData){
data.countries=countriesData;
dbro.many("SELECT * FROM categorias")
.then(function(categoriesData){
data.categories=(categoriesData)
console.log(data);
res.render('layout', data);
res.end();
})
.catch(function(err){
console.log("error while fetching categories data");
})
})
.catch(function(err){
console.log("error while fetching countries data",err);
});
Run Code Online (Sandbox Code Playgroud)
不知怎的,我认为这是不对的.如果我需要在返回回调之前获得许多查询的结果怎么办?几个then/catch的嵌套变得丑陋.目标是在呈现页面之前准备好所有数据(在Express中)
vit*_*y-t 21
pg-promise文档有很多关于如何执行多个查询的示例.
初始化
const pgp = require('pg-promise')(/* initialization options */);
const db = pgp('postgres://username:password@host:port/database');
Run Code Online (Sandbox Code Playgroud)
当查询相互依赖时,我们应该在任务中链接它们:
db.task('get-user-events', async t => {
const user = await t.one('select * from users where id = $1', 123);
return t.any('select * from events where login = $1', user.name);
})
.then(data => {
// data = result from the last query;
})
.catch(error => {
// error
});
Run Code Online (Sandbox Code Playgroud)
当查询没有依赖关系时,我们应该在任务中作为批处理执行它们:
db.task('get-everything', async t => {
const users = await t.any('select * from users');
const count = await t.one('select count(*) from events', [], a => +a.count);
return {users, count};
})
.then({users, count} => {
})
.catch(error => {
// error
});
Run Code Online (Sandbox Code Playgroud)
当查询更改数据时,我们应该用tx替换task以进行事务处理.
请注意,我强调每个语句都带有"should",因为您可以执行任务或事务之外的所有内容,但由于数据库连接的管理方式,因此不建议这样做.
当您需要根据HTTP请求执行单个查询时,您应该只对根协议(db对象)执行查询.一次多个查询应始终在任务/事务中执行.
另请参阅链接查询,其主要点位于底部:
如果您不遵循建议的方法,由于并行分配更多连接,您的应用程序将在较小负载下表现更好,但在负载较重的情况下,它将很快耗尽连接池,从而削弱应用程序的性能和可伸缩性.
UPDATE
从pg-promise v7.0.0 开始,我们可以在一个命令中从多个查询中提取结果,这比以前的所有解决方案都要高效得多:
db.multi('SELECT * FROM users;SELECT count(*) FROM events')
.then({users, count} => {
})
.catch(error => {
// error
});
Run Code Online (Sandbox Code Playgroud)
或者,如果您正在使用db,那么:
const pgp = require('pg-promise')(/* initialization options */);
const db = pgp('postgres://username:password@host:port/database');
Run Code Online (Sandbox Code Playgroud)
查看新方法multi和multiResult.
| 归档时间: |
|
| 查看次数: |
6902 次 |
| 最近记录: |