JS mysql query result

Viewed 56

I'm quite new in Node JS and I'm trying use a mysql DB.

I have try different thing like using promise to get the result of my query but the await is skip and the promise is pending.

I'm kinda lost if someone can explain me how it works.

import * as CMD from "../command/importCommand.js";

export class Message {
    constructor(bot, database) {
        this.bot = bot;
        this.db = database;
    }

    eventHandler(msg) {
        const guild = msg.guild;
        const prefix = this.db.getPrefixFromGuild(guild);
        console.log(prefix);
        //
        //
    }
}
import * as mysql from "mysql";

export class Database {

    constructor() {
        this.db = new mysql.createConnection({
            host: process.env.DB_HOST,
            user: process.env.DB_USER,
            password: process.env.DB_PASSWORD,
            database: process.env.DB_NAME
        });

        this.db.connect(err => {
            if (err) throw err;
            console.log('DB connected');
        });
    }

    async getPrefixFromGuild(guild) {
        let prefix = await this.getPrefixFromGuildId(guild.id);
        return prefix;
    }

    async getPrefixFromGuildId(guildId) {
        let prefix = await this.query("select prefix from serveur where id_serveur=" + guildId + ";");
        return prefix;
    }
    query(sql) {
        return this.db.query(sql, (err, rows) => {
            if (err)
                throw err;
            console.log(rows);
            return rows;
        });
    }
}
1 Answers

Your eventHandler is not an async function and does not await the promise returned from getPrefixFromGuild(). The console.log() statement just logs the promise, not its result. Try this:

async eventHandler(msg) {
    const guild = msg.guild;
    const prefix = await this.db.getPrefixFromGuild(guild);
    console.log(prefix);
}

Please also note that if you access an instance of your Database class right after creation, it might not be initialized since the constructor ist not waiting for the conntect() to complet (it shouldn't but you should find another way to prevent access to an uninitialized Database object).

Related