I've tried to call 2 queries toward postgres with nodeJS in a sequential way. I came to this code. However I'm not really happy with it, it seems overcomplicated to do a simple thing. Is there a simpler way to do what I'm trying to do ?
Basically, I try to print "before 1st" on console then execute the select now(), then print the results, then write "after 1st", then print "before 2nd" then execute select now(), then print the results, then write "after 2nd"
getConn().
then(async() => {
console.log("before 1st selectNow2")
await selectNow2()
console.log("after 1st selectNow2")
})
.then(async() => {
console.log("before 2nd selectNow2")
await selectNow2()
console.log("after 2nd selectNow2")
})
async function selectNow2() {
await client.query('SELECT NOW()')
.then(res => {
console.log(res.rows[0])
})
.catch(err => {
console.log(err.stack)
})
}
You do not need to use await
and then()
in the same statement inside selectNow2()
. Since you are using await
, you will not be returning a promise which means the returned value will not have the method then().
performQuery().then(() => {
console.log("DONE");
});
async function performQuery(){
await getConn();
console.log("before 1st selectNow2");
await selectNow2();
console.log("after 1st selectNow2");
console.log("before 2nd selectNow2");
await selectNow2();
console.log("after 2nd selectNow2");
}
async function selectNow2) {
try{
await client.query('SELECT NOW()');
console.log(res.rows[0])
}catch(err){
console.log(err.stack)
}
}