Search code examples
javascriptnode.jsdiscorddiscord.jsnode-mysql2

pool closed mysql2 discord bot


good day
When trying to add data to the database, it throws an error UnhandledPromiseRejectionWarning: Error: Pool is closed
It is necessary to upload the message id to the database
If there is another way to send mysql queries in order, I'm ready to consider, but for now I like this method more, I just need to understand the cause of the problem and find a solution

const mysql = require("mysql2");
const mysql_cfg = require("../mysql_cfg.json");

module.exports = {
  name: "test",
  execute(message, args) {
    let lider_id = message.author.id;
    var con = mysql.createPool(mysql_cfg).promise();

    message.delete();

    con
      .execute(`SELECT id, date_unblock FROM blocks WHERE id = "${lider_id}"`)
      .then((result) => {
        message.channel.send("test").then((msg) => {
          setTimeout(function () {
            msg.edit("@here").then(function (message) {
              message.react("+");
            });
          }, 1000);

          return con.execute(`INSERT INTO events (id) VALUES ("${msg.id}")`);
        });
      })
      .then(() => {
        con.end();
      })
      .catch((err) => {
        console.log(err);
      });
  },
};


Solution

  • You aren't waiting for the message edits, etc. to finish executing before you start closing the pool.

    The .then() jungle is pretty wild, so reworking things to async/await, this becomes

    const mysql = require("mysql2");
    const mysql_cfg = require("../mysql_cfg.json");
    
    module.exports = {
      name: "test",
      async execute(message, args) {
        const lider_id = message.author.id;
        const con = mysql.createPool(mysql_cfg).promise();
        message.delete();
    
        const result = await con.execute(`SELECT id, date_unblock FROM blocks WHERE id = "${lider_id}"`);
        const msg = await message.channel.send("test");
    
        setTimeout(async function () {
          const message = await msg.edit("@here");
          message.react("+");
        }, 1000);
    
        await con.execute(`INSERT INTO events (id) VALUES ("${msg.id}")`);
        con.end();
      },
    };