【问题标题】:Discord.js v13, issue with asynchronous codeDiscord.js v13,异步代码问题
【发布时间】:2022-01-01 21:40:20
【问题描述】:

所以我的问题是,尽管使用了异步函数,但我的代码仍会像同步代码一样运行。所以有些命令没有通过或被大大延迟,这显然是不应该的。

这是在“interactionCreate”事件上执行的代码:

const Discord = require("discord.js");

/**
 * 
 * @param {Discord.Client} client 
 * @param {Discord.Interaction} interaction 
 * @returns 
 */
module.exports = async (client, interaction) => {
    if (interaction.isCommand()) {
        const { commandName } = interaction;

        const command = client.commands.get(commandName);

        if (command) command.execute(client, interaction);
    }
}

这是一个命令:

const Discord = require('discord.js');
const util = require('util');
const search = util.promisify(require('g-i-s'));
const Colors = require("../src/colors");

module.exports = {
    name: "salmon",
    description: "Sends a random picture of a salmon",
    /**
    * 
    * @param {Discord.Client} client 
    * @param {Discord.CommandInteraction} interaction 
    */
    async execute(client, interaction) {
        await interaction.deferReply();

        const results = await search("salmon");

        const number = Math.floor(Math.random() * results.length)
        const embed= new Discord.MessageEmbed()
            .setColor(Colors.PINK)
            .setTitle(`Salmon number ${number}.`)
            .setImage(results[number].url);

        interaction.editReply({ embeds: [embed] });
    }
}

执行上面的代码会在其他命令上产生“滞后”。这对我来说通常不是问题,但这会影响整个代码,因此使用“播放音乐”命令非常不稳定,因为每次有人使用一个负载有点重的命令时,会听到可听见的延迟。

我已经用更重的负载进行了测试,以使延迟保持更长时间,并且机器人不会执行新命令。虽然我觉得我没有做错什么。为什么我的 async execute 函数的行为不像异步函数?还是我错过了什么?

【问题讨论】:

    标签: javascript node.js asynchronous async-await discord.js


    【解决方案1】:

    也许您应该尝试使用execute async 而不是async execute

    【讨论】:

    • execute async() { } 无效。我尝试了execute: async() => { },但它仍然无法正常工作。我不明白为什么它不起作用。我会尝试创建一个新项目并测试它的行为是否相同......
    • 奇怪...好吧我会尝试搜索其他问题
    • 可能与module.exports有关?虽然我不明白为什么会这样。我想需要注意的重要一点是它曾经工作但停止了?虽然什么都没有改变,所以我真的很困惑,没有想法
    • 把你的 index.js 文件发给我(或编辑帖子)
    猜你喜欢
    • 2022-01-03
    • 2021-12-01
    • 2022-07-19
    • 2021-11-13
    • 2021-10-23
    • 2020-07-26
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多