池关闭 mysql2 discord bot

问题描述

美好的一天
尝试向数据库添加数据时,会抛出错误 UnhandledPromiseRejectionWarning: Error: Pool is closed
需要将消息id上传数据库
如果有其他方式按顺序发送mySQL查询,我准备考虑,但目前我更喜欢这种方式,我只需要了解问题的原因并找到解决方

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

解决方法

在开始关闭池之前,您不是在等待消息编辑等完成执行。

.then() 丛林非常狂野,因此将内容重做 async/await,这变成了

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