【问题标题】:Javascript object returning undefined inside a functionJavascript对象在函数内返回未定义
【发布时间】:2021-07-07 05:12:18
【问题描述】:

今天我试图用一个函数从 mysql 获取一些数据,当我 console.log 函数内的值时,都正确返回,但如果我 return <value>,它返回 undefined(rows[0] 是一个对象),例如:

function getData(userID, guildID) {
    connection.connect();
    this.guildID = guildID ?? null
    this.userID = userID ?? null
    connection.query(`SELECT * FROM data_${this.guildID} WHERE id = '${this.userID}'`, (err, rows, fields) => {
        if(err) throw err;
        connection.end()
        this.data = rows[0]
        return this.data;
    })
}

当我console.log(getData(etc, etc))时返回未定义

但如果我这样做:

function getData(userID, guildID) {
    connection.connect();
    this.guildID = guildID ?? null
    this.userID = userID ?? null
    connection.query(`SELECT * FROM data_${this.guildID} WHERE id = '${this.userID}'`, (err, rows, fields) => {
        if(err) throw err;
        connection.end()
        this.data = rows[0]
        console.log(this.data);
    })
}

它工作得非常好,记录如下:

RowDataPacket {
  id: '573991320897716224',
  bank: '0',
  wallet: '0',
  unlimited: '0'
}

【问题讨论】:

    标签: javascript mysql arrays object


    【解决方案1】:

    发生这种情况是因为行数据在 connection.query 的回调中,并且您的 getData 函数已完成自身执行。

    简单来说,现在发生的事情是您期望 getData 函数返回结果,但结果在回调中,在您的 getData 函数执行时尚未完成执行

    您可以做的是创建一个承诺并在回调完成检索数据后解决它。例如

    async function getData(userID, guildID) {
        connection.connect();
        this.guildID = guildID ?? null
        this.userID = userID ?? null
        return await queryDatabase(connection, {guildID: this.guildID, userID: this.userID})
    }
    
    
    function queryDatabase(connectionObj, payload) {
        return new promise((resolve, reject) => {
            connectionObj.query(`SELECT * FROM data_${payload.guildID} WHERE id = '${payload.userID}'`, (err, rows, fields) => {
            if(err) reject(err);
            connectionObj.end()
            resolve(rows[0]);
            })
        });
    }
    

    【讨论】:

    • 非常感谢您的帮助!!这解决了我的问题,感谢它
    猜你喜欢
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 2012-01-02
    相关资源
    最近更新 更多