【发布时间】: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