Reputation: 77
So I am not sure how node-pg works but I have been trying to make it work by looking around, trying things and reading the documentation for a while now. What I want to achieve is to be able to send multiple queries at different times but it always throws errors after i send the first one if I dare coding a second one in. This question has been asked multiple times online but I dont see any helpful answers. I can use pooling if its necessary (that had issues too).
What works now: (Its on heroku so i have to use process.env.DATABASE_URL)
const { Client } = require('pg');
const client = new Client({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
}
});
client.connect()
client
.query('SELECT * FROM test WHERE....')
.then(results => {
console.log(results);
}
.catch(err => {
console.log(err.stack)
})
What I 'm trying to do:
const { Client } = require('pg');
const client = new Client({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
}
});
client.connect()
client
.query('SELECT * FROM test1 WHERE....')
.then(results => {
console.log("FIRST RESULTS: "results);
}
.catch(err => {
console.log(err.stack)
})
.query('SELECT * FROM test2 WHERE....')
.then(results => {
console.log("SECOND RESULTS: "results);
}
.catch(err => {
console.log(err.stack)
})
Upvotes: 3
Views: 2670
Reputation: 371178
When you .query
, a Promise is returned, and Promises don't have .query
methods - all you can do with the Promise is call .then
or .catch
on it (or .finally
, sometimes).
If you want to make a new query after the old finishes, call client.query
inside a .then
:
client
.query('SELECT * FROM test1 WHERE....')
.then(results => {
console.log("FIRST RESULTS: " + results);
})
.then(() => client.query('SELECT * FROM test2 WHERE....'))
.then(results => {
console.log("SECOND RESULTS: " + results);
})
.catch(err => {
// better to handle errors at the end, probably
console.log(err.stack)
})
If the second query depends on the first's result, consider using an async
function instead, to make the code flatter and more readable.
If the second query doesn't depend on the first's result, consider using Promise.all
instead, so that both queries can be made at once, rather than having to wait for the first to finish first.
Upvotes: 2