函数似乎返回未定义的值,即使在函数内部,返回的变量具有值

时间:2020-05-05 01:54:18

标签: javascript node.js

我正在尝试获取一个将布尔值返回给调用它的值的函数,无论我尝试什么,我似乎都无法使其正常工作(这在主脚本中所需的脚本中运行)中另一个文件),这是我当前的代码:

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;
    })
}

让我困惑的是当我运行类似这样的东西时:

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
})

一切正常。

0 个答案:

没有答案