-1

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()?

Targaryen
  • 1,081
  • 2
  • 17
  • 30
  • `.catch(ex => { throw ex; })` is as [pointless as `.then(value => value)`](https://stackoverflow.com/q/41089122/1048572) – Bergi Sep 26 '22 at 17:03

1 Answers1

1

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();
    }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375