I connect to a Postgres database in Node and I get a return value from the database. However, when I try to pass that value to another function, the value is undefined
. Check out this code:
async function doDbCall(queryString) {
await client.connect()
.then(async () => {
await client.query(queryString)
.then(dbRes => {
console.log("dbDoCall - dbRes", dbRes.rows[0]);
return dbRes;
})
});
}
Here is the calling function:
async function testTheDb() {
try {
const myReturnVal = await dbConn.doDbCall("SELECT NOW() as now");
console.log("db val:", myReturnVal);
}
catch(ex) {
console.log("db err", ex.message);
}
}
In the console.log in doDbCall()
on the query.then success, I get a value in dbRes.rows[0]. The console.log shows dbDoCall - dbRes { now: 2022-09-26T16:47:14.465Z }
. So I return that value.
However, in the testTheDb()
function, I have another console log where I log the value of myReturnVal
. The result of that log shows db val: undefined
.
My question is this: Why is myReturnVal
null in testTheDb()?
CodePudding user response:
You should not mix async
/await
syntax with .then()
calls. Your problem is that neither the doDbCall
function nor the async () => {…}
callback do return anything, your only return
keyword is nested inside a nested then
callback.
You should write either
function doDbCall(queryString) {
return client.connect()
.then(() => {
return client.query(queryString);
})
.then(dbRes => {
console.log("dbDoCall - dbRes", dbRes.rows[0]);
return dbRes;
})
.finally(() => {
client.end();
});
}
or
async function doDbCall(queryString) {
try {
await client.connect()
const dbRes = await client.query(queryString);
console.log("dbDoCall - dbRes", dbRes.rows[0]);
return dbRes;
} finally {
client.end();
}
}