Create MessageCollector.next (#761)

Allows using await with message collectors (ES7)
Hydrabolt approved™
This commit is contained in:
Programmix
2016-10-01 12:29:15 -07:00
committed by Amish Shah
parent 530035e14b
commit 34168eb832

View File

@@ -92,6 +92,34 @@ class MessageCollector extends EventEmitter {
return false;
}
/**
* Returns a promise that resolves when a valid message is sent. Rejects
* with collected messages if the Collector ends before receiving a message.
* @type {Promise<Message>}
* @readonly
*/
get next() {
return new Promise((resolve, reject) => {
const cleanup = () => {
this.removeListener(onMessage);
this.removeListener(onEnd);
};
const onMessage = (...args) => {
cleanup();
resolve(...args);
};
const onEnd = (...args) => {
cleanup();
reject(...args);
};
this.once('message', onMessage);
this.once('end', onEnd);
});
}
/**
* Stops the collector and emits `end`.
* @param {string} [reason='user'] An optional reason for stopping the collector