Currently I have the following code to get the results of two queries
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);
});
Somehow I think this is not right. What if I need to get the results of many queries before returning the callback? The nesting of several then/catch becomes hideous. The objective is to have all the data ready before rendering a page (in Express)
pg-promise documentation has plenty of examples of how to execute multiple queries.
Initialization
When queries depend on each other we should use a task:
When queries have no dependencies between them:
And when the queries change the data, we should replace task with tx for transaction.
Note that I emphasized each statement with "should", as you can execute everything outside of tasks or transactions, but it is not recommended, due to the way database connections are managed.
You should only execute queries on the root protocol (
db
object) when you need to execute a single query per HTTP request. Multiple queries at once should always be executed within tasks/transactions.See also Chaining Queries, with its main point at the bottom there:
UPDATE
Starting from pg-promise v7.0.0 we can pull results from multiple queries in a single command, which is much more efficient than all of the previous solutions:
See new methods multi and multiResult.