mirror of
https://github.com/danbulant/discord.js
synced 2026-05-27 14:02:02 +00:00
feat(Collector): allow collectors to be consumed by for-await-of loops (#3269)
This commit is contained in:
parent
7fae6e5bca
commit
6d3c55b68c
2 changed files with 32 additions and 0 deletions
|
|
@ -196,6 +196,37 @@ class Collector extends EventEmitter {
|
|||
if (reason) this.stop(reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows collectors to be consumed with for-await-of loops
|
||||
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of}
|
||||
*/
|
||||
async *[Symbol.asyncIterator]() {
|
||||
const queue = [];
|
||||
const onCollect = item => queue.push(item);
|
||||
this.on('collect', onCollect);
|
||||
|
||||
try {
|
||||
while (queue.length || !this.ended) {
|
||||
if (queue.length) {
|
||||
yield queue.shift();
|
||||
} else {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await new Promise(resolve => {
|
||||
const tick = () => {
|
||||
this.off('collect', tick);
|
||||
this.off('end', tick);
|
||||
return resolve();
|
||||
};
|
||||
this.on('collect', tick);
|
||||
this.on('end', tick);
|
||||
});
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.off('collect', onCollect);
|
||||
}
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return Util.flatten(this);
|
||||
}
|
||||
|
|
|
|||
1
typings/index.d.ts
vendored
1
typings/index.d.ts
vendored
|
|
@ -363,6 +363,7 @@ declare module 'discord.js' {
|
|||
public handleCollect(...args: any[]): void;
|
||||
public handleDispose(...args: any[]): void;
|
||||
public stop(reason?: string): void;
|
||||
public [Symbol.asyncIterator](): AsyncIterableIterator<V>;
|
||||
public toJSON(): object;
|
||||
|
||||
protected listener: Function;
|
||||
|
|
|
|||
Loading…
Reference in a new issue