You have 2 options:
If you want to continue using the basic driver, you will have to use the result callback, and then nest those in order to use result in the next query:
connection.query(query1, values1, function(err1, result1) {
// check if(err1) first, then:
connection.query(query2, values2, function(err2, result2) {
// check if(err2) first, then:
connection.query(query3, values3, function(err3, result3) {
// check if(err3) first, then:
cb(result1, result2, result3);
});
});
});
The alternative approach is to use promises (pg-promise) when you can chain calls like this:
db.query(query1, values2)
.then(data => {
return db.query(query2, values2);
})
.then(data => {
return db.query(query3, values3);
})
.catch(error => {});
Although the right approach for pg-promise in this case is via method task
:
db.task(t => {
const result = {};
return t.query(query1, values1)
.then(data => {
result.a = data;
return t.query(query2, values2);
})
.then(data => {
result.b = data;
return t.query(query3, values3);
});
.then(data => {
result.c = data;
return result;
});
})
.than(data => {
// data = {a, b, c}
})
.catch(error => {});
The second approach automatically gives you access to the modern syntax of ES6 and ES7 when executing multiple queries at a time, as you can do:
For ES6:
db.task(function * (t) {
let a = yield t.query(query1, values1);
let b = yield t.query(query2, values2);
let c = yield t.query(query3, values3);
return {a, b, c};
})
.than(data => {
// data = {a, b, c}
})
.catch(error => {});
For ES7 / Babel:
db.task(async t => {
let a = await t.query(query1, values1);
let b = await t.query(query2, values2);
let c = await t.query(query3, values3);
return {a, b, c};
})
.than(data => {
// data = {a, b, c}
})
.catch(error => {});