[whatwg/dom] once() and on() async utilities for EventTarget (Issue #1038)

A while back Node.js introduced the [`once()`](https://nodejs.org/dist/latest-v17.x/docs/api/events.html#eventsonceemitter-name-options) and [`on()`](https://nodejs.org/dist/latest-v17.x/docs/api/events.html#eventsonemitter-eventname-options) utility functions for Node.js' `EventEmitter` object. They are essentially just promise-based alternatives to adding a callback listener for an event. They've proven to be so useful in practice that I'd like to propose adding similar utilities for `EventTarget`

Essentially,

```js
const ac = new AbortController();
const eventTarget = new EventTarget();
setTimeout(() => eventTarget.dispatchEvent(new Event('foo')), 1000);
// EventTarget.once() returns a Promise that is resolved the next time the event is dispatched.
await EventTarget.once(eventTarget, 'foo', { signal: ac.signal }); 
```

and

```js
const ac = new AbortController();
const eventTarget = new EventTarget();
setInterval(() => eventTarget.dispatchEvent(new Event('foo')), 1000);
// EventTarget.on() returns an async iterator that iterates each time the event is dispatched.
for await (const ev of EventTarget.on(eventTarget, 'foo', { signal: ac.signal })) {
  // ...
}
```



-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/1038

Received on Wednesday, 1 December 2021 20:24:16 UTC