-
-
Notifications
You must be signed in to change notification settings - Fork 4k
Description
Which application or package is this feature request for?
discord.js
Feature
Right now, as I understand it, the documented way to close out a Client
after it's done is destroy()
:
const client = new Client({ intents: [/* ... */] });
await client.login(/* ... */);
// ... (use the client) ...
await client.destroy();
One gotcha is that if the ( use the client )
bit throws, the await client.destroy()
won't run - unless you try
/catch
or try
/(catch
/)finally
). This is a common gotcha in async code.
Explicit Resource Management is a TC39 proposal to add explicit syntax for situations where a resource should have some method called upon disposal. It's stage 3 now and supported in TypeScript >=5.2.
Ideal solution or implementation
Proposal: can the BaseClient
class be given a [Symbol.asyncDispose]
method that calls this.destroy()
?
class BaseClient<Ready extends boolean = boolean> {
// ... (existing class fields) ...
async [Symbol.asyncDispose]() {
await this.destroy();
}
}
That way we'd be able to use clients like:
await using client = new Client({ intents: [/* ... */] });
...and be more assured that the client
's .destroy()
will be called and awaited when done.
Alternative solutions or implementations
For now, we can somewhat shim this in with:
class DisposableClient<Ready extends boolean = boolean> extends Client<Ready> {
async [Symbol.asyncDispose]() {
await this.destroy();
}
}
await using client = new DisposableClient({
intents: [GatewayIntentBits.Guilds],
});
Other context
I made a small standalone package containing this suggested DisposableClient
: https://github.com/JoshuaKGoldberg/disposable-discord-client -> https://www.npmjs.com/package/disposable-discord-client