While booting my Node.js app, I want to make a couple of synchronous calls to the PostgreSQL database to check some things before continuing the control flow. How can I achieve this using the node-postgres package?
5 Answers
The only way to synchronize calls is to nest them in callbacks:
function init() {
pg.connect('tcp://user@host/db', function(err, client, done) {
client.query("SELECT column FROM table", function(err, result) {
// check some things...
client.query("SELECT column FROM other_table", function(err, result) {
// check some other things...
main(); // proceed with flow...
}
});
}
}
function main() {
// main logic
}
This can be a pain, and would be trivial in some other languages, but it is the nature of the beast.
Comments
brianc (author of node-postgres) commented here, that
"The only way to do sync queries is to use pg-native and use the
syncvariant of the methods. Using pure javascript client it is impossible to do sync queries because of how node works."
Hope this helps...
1 Comment
fider
This is the only valid answer for question in topic:
"How to make a synchronous query (blocking call) with node-postgres?"You can do this by using pg-pool in combination with asyncawait:
var suspendable = async (function defn(a, b) {
var name1 = await(pool.query('select $1::text as name', ['foo']));
console.log(name1.rows[0].name, 'says hello');
var name2 = await(pool.query('select $1::text as name', ['bar']));
console.log(name2.rows[0].name, 'says hello');
});
suspendable();