Skip to content

Commit bbd2c7d

Browse files
authored
Allow for once to return a promise
To start some discussion regarding nodejs/node#20909 (comment)
1 parent 2efe30b commit bbd2c7d

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

index.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -232,12 +232,18 @@ EventEmitter.prototype.on = function on(event, fn, context) {
232232
* Add a one-time listener for a given event.
233233
*
234234
* @param {(String|Symbol)} event The event name.
235-
* @param {Function} fn The listener function.
235+
* @param {Function} [fn] The listener function.
236236
* @param {*} [context=this] The context to invoke the listener with.
237-
* @returns {EventEmitter} `this`.
237+
* @returns {EventEmitter|Promise} `this` if a listener was passed for chaining,
238+
* or a promise for the event if none was passed.
238239
* @public
239240
*/
240241
EventEmitter.prototype.once = function once(event, fn, context) {
242+
if (typeof fn !== 'function' && typeof Promise === 'function') {
243+
return new Promise(function executor(resolve, reject) {
244+
addListener(this, event, resolve, this, true);
245+
}.bind(this));
246+
}
241247
return addListener(this, event, fn, context, true);
242248
};
243249

0 commit comments

Comments
 (0)