Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/nodejs/node.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJames M Snell <jasnell@gmail.com>2020-08-24 23:11:23 +0300
committerNode.js GitHub Bot <github-bot@iojs.org>2020-08-31 18:09:57 +0300
commit883fc779b637732b18e2d0e6b1f386cebb37e93c (patch)
tree3451371d49699a9ce78550851a535c4bce435f42 /doc/api/events.md
parent37a8179673590af10b9e8e413388adffc21ba713 (diff)
events: allow use of AbortController with once
Allows an AbortSignal to be passed in to events.once() to cancel waiting on an event. Signed-off-by: James M Snell <jasnell@gmail.com> PR-URL: https://github.com/nodejs/node/pull/34911 Reviewed-By: Denys Otrishko <shishugi@gmail.com> Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Diffstat (limited to 'doc/api/events.md')
-rw-r--r--doc/api/events.md30
1 files changed, 29 insertions, 1 deletions
diff --git a/doc/api/events.md b/doc/api/events.md
index 3004d5bbb3c..7c756e6df9e 100644
--- a/doc/api/events.md
+++ b/doc/api/events.md
@@ -825,7 +825,7 @@ class MyClass extends EventEmitter {
}
```
-## `events.once(emitter, name)`
+## `events.once(emitter, name[, options])`
<!-- YAML
added:
- v11.13.0
@@ -834,6 +834,9 @@ added:
* `emitter` {EventEmitter}
* `name` {string}
+* `options` {Object}
+ * `signal` {AbortSignal} An {AbortSignal} that may be used to cancel waiting
+ for the event.
* Returns: {Promise}
Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given
@@ -892,6 +895,31 @@ ee.emit('error', new Error('boom'));
// Prints: ok boom
```
+An {AbortSignal} may be used to cancel waiting for the event early:
+
+```js
+const { EventEmitter, once } = require('events');
+
+const ee = new EventEmitter();
+const ac = new AbortController();
+
+async function foo(emitter, event, signal) {
+ try {
+ await once(emitter, event, { signal });
+ console.log('event emitted!');
+ } catch (error) {
+ if (error.name === 'AbortError') {
+ console.error('Waiting for the event was canceled!');
+ } else {
+ console.error('There was an error', error.message);
+ }
+ }
+}
+
+foo(ee, 'foo', ac.signal);
+ac.abort(); // Abort waiting for the event
+```
+
### Awaiting multiple events emitted on `process.nextTick()`
There is an edge case worth noting when using the `events.once()` function