1

Today I was trying to get some data from mysql with a function, and when i console.log the values inside the function, all returns properly, but if i return <value>, it returns undefined (rows[0] is an object), for example:

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

returns undefined when i console.log(getData(etc, etc))

but if i do:

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

it works perfectly fine, which logs:

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

1 Answer 1

2

This is happening because the rows data is inside the callback of connection.query and your getData function is finished executing itself.

In simple terms what's happening right now is that you are expecting getData function to return the result but the result is in the callback which has not finished execution by the time your getData function is executed

What you may do is create a promise and resolve it once the callback has finished retrieving the data. e.g

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]);
        })
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for your help!! this solved my issue, appreciate it <3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.