簡體   English   中英

Discord.js 中的集合對象設置成功后清空

[英]Collection object in Discord.js emptying after being successfully set

所以我在 Discord.js 庫中遇到了我的集合對象的問題。 我正在研究一個命令和事件處理程序,以根據每個目錄中寫入的文件填充一組命令和事件。 只要我在 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
  }
}

您可能不知道,但是您將每個commandFileseventFiles項目映射到一個 Promise。 為了確保在調用console.log(this)之前異步函數實際上已經完成,你需要等待 map 函數返回的 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

留下 'dangling' Promises 經常會導致一些意想不到的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM