1

I'm trying to get a function to return a boolean value to that which called it and no matter what I try I cannot seem to get it to work (this is running in a script that is required by a main script in another file), here is my current code:

const { Client } = require('pg')
const client = new Client({
    connectionString: process.env.DATABASE_URL,
    ssl: true,
});

async function checkschema(name) {
    try {
        client.connect()
        client.query(`SELECT EXISTS(SELECT schema_name FROM information_schema.schemata WHERE schema_name = '${name}');`, (err, res) => {
            if (err) throw err;
            let result = JSON.stringify(res.rows[0]["exists"])
            console.log("result is: "+result) // logs "result is: true/false"
            client.end()
            return result
        })
    } catch(err) {
        console.log("error: "+JSON.stringify(err))
    }
}

module.exports.getdata = (serverid, userid) => {
    checkschema(serverid).then((result) => {
        console.log("result 2 is: "+result) // logs "result 2 is: Undefined"
        return result;
    })
}

What confuses me is when I run something like this:

async function check() {
    let result = true
    console.log("result 1 is: "+result) // result is: true
    return result

}

check().then((result) => {
    console.log("result 2 is: "+result) // result is: true
})

everything works.

W0LFB0MB
  • 55
  • 10
  • You'll want to use the promise-based version of [`client.query()`](https://node-postgres.com/features/queries) so you can return that promise from `checkschema`. Right now, your function returns nothing – Phil May 05 '20 at 01:57
  • 1
    Hi @Phil Do you mean using client.query like `res = await client.query()`or maybe something like `client.query() => Promise`? – W0LFB0MB May 05 '20 at 02:03
  • The first one, `res = await.client.query()` – Phil May 05 '20 at 02:06
  • @JaromandaX Yeah, I've never tried doing something like this before or even used asynchronous functions and promises. – W0LFB0MB May 05 '20 at 02:06
  • In modern JS, avoid using APIs that use the old-school `(err, res) => { ... }` callback. Most offer promise-based versions these days – Phil May 05 '20 at 02:08
  • @Phil Thanks for the info, though how would I extract and return the data? I'm new to promises and have hardly any clue on how to use them – W0LFB0MB May 05 '20 at 02:11
  • Your code should pretty much look the same except you won't have it within the `(err, res)` callback – Phil May 05 '20 at 02:15

0 Answers0