Search code examples
javascriptmysqlasync-awaitmysqljs

How to wait to pending promises to return


Today I was getting so many Promise { < pending > } and I don't know why, so i tried to console.log() a few things, and i discovered that getData() is returning before queryDatabase(), can someone explain me why, and what can I do it to fix it? I need queryDatabase() data to return before getData() so the promise doesen't returns pending, here is my code:

(connection is a MySQL connection pool)

async function getData(userID, guildID) {
    this.guildID = guildID ?? null
    this.userID = userID ?? null
    this.data = await queryDatabase({guildID: this.guildID, userID: this.userID})
    console.log('foo 2')
    return this.data;
    
}

function queryDatabase(payload) {
    connection.getConnection((sqlerr, con) => {
        return new Promise((resolve, reject) => {
            con.query(`(My mysql query)`, (err, rows, fields) => {
                if(err) reject(err);
                con.end()
                resolve(rows[0]);
                console.log('foo')
            })
        });
    })
}

Solution

  • I found out the issue thanks to John, I put the promise in getConnection isntead of queryDatabase, so the function wasn't returning anything, thank you all for the help <3