所以我在Discord.js库中的collections对象遇到了问题。我正在开发一个命令和事件处理程序,根据每个目录中写入的文件来填充命令和事件的集合。只要我在map函数中进行检查,每个集合似乎都能正确填充。在第二个映射完成后,我填充的第二个集合立即变为空,但第一个集合仍保持设置状态。
如果我颠倒它们的设置顺序,问题将变为第二个设置的集合。因为它们在映射中调试时都设置得很好,或者如果它们是先设置的,我相信它与目录无关,也与它们正在导入的文件无关。我怀疑这在某种程度上与集合如何在我不知道的对象上工作有关。
对此有任何见解都会很棒!
import { Command, Event, Config } from "../Interfaces/index"
import { Client, Collection, Intents } from "discord.js"
import glob from "glob";
import { promisify } from "util";
const globPromise = promisify(glob)
class Bot extends Client {
public events: Collection<string, Event> = new Collection()
public commands: Collection<string, Command> = new Collection()
public aliases: Collection<string, Command> = new Collection()
public config: Config
public constructor() {
super({ ws: { intents: Intents.ALL } })
}
public async init(config: Config): Promise<void> {
this.config = config
this.login(this.config.token)
const commandFiles: string[] = await globPromise(`${__dirname}/../Commands/**/*.ts`)
commandFiles.map(async (filePath: string) => {
const { command }: { command: Command } = await import(filePath)
this.commands.set(command.name, command)
if (command.aliases?.length !== 0) {
command.aliases?.forEach((alias) => {
this.aliases.set(alias, command)
})
}
})
const eventfiles: string[] = await globPromise(`${__dirname}/../Events/**/*.ts`)
eventfiles.map(async (filePath: string) => {
const { event }: { event: Event } = await import(filePath)
this.events.set(event.name, event)
console.log(this) // Events and commands collection are populated
})
console.log(this) // Events collection is empty and commands collection is populated
}
}
您可能不知道,但您将每个commandFiles
和eventFiles
项都映射到了Promise。为了确保异步函数在调用console.log(this)
之前实际完成,您需要等待映射函数返回的Promises。
要等待从map
返回的每个项目,请将调用包装在Promise.all
:中
const commandFiles: string[] = await globPromise(`${__dirname}/../Commands/**/*.ts`)
await Promise.all(
commandFiles.map(async (filePath: string) => {
...
})
);
const eventfiles: string[] = await globPromise(`${__dirname}/../Events/**/*.ts`)
await Promise.all(
eventfiles.map(async (filePath: string) => {
...
})
);
console.log(this) // collections should be populated at this point
// because you awaited the `map` results
留下"悬着的"承诺往往会导致一些意想不到的错误。