# Event async / await

**URL:** <https://es.discourse.group/t/event-async-await/1618>\
**Category:** 💡 Ideas\
**Tags:** proposal\
**Created:** [February 18, 2023, 2:19pm UTC](https://es.discourse.group/t/event-async-await/1618 "2023-02-18T14:19:34Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![bergus](https://yyz2.discourse-cdn.com/free1/user_avatar/es.discourse.group/bergus/32/152_2.png) [@bergus](https://es.discourse.group/u/bergus)\
**Post date:** [February 19, 2023, 12:25am UTC](https://es.discourse.group/t/event-async-await/1618/5 "2023-02-19T00:25:03Z")

</div>

> [@0X-JonMichaelGalindo](#):
>
> `listenForEvent( eventName )` would wrap a Promise around a single-use event listener.

You can do that even simpler, see e.g. [ecmascript 6 - Pausing javascript async function until user action - Stack Overflow](https://stackoverflow.com/a/45356249/1048572) :

```js
EventTarget.prototype.listenForEvent = function(type) {
  return new Promise(resolve => {
    element.addEventListener(type, resolve, {once: true});
  });
};

```

> [@0X-JonMichaelGalindo](#):
>
> And the async iterator generator `streamEvents` would yield a stream of those Promises:

That's probably a bad idea. An async iterator runs only as fast as it is consumed, but events fire at any rate. It would be quite error-prone to write code like

```javascript
for await (const event of document.body.streamEvents("scroll")) {
    await delay(50);
    console.log("Debounced scrolling: ", event);
}
console.log("Done"); // dead code?

```

since the async iterator would not be able to handle the backpressure. Should it just drop events? Should it buffer them? Neither is really desirable.  
Using `for await` leads to users writing sequential code, `addEventListener` allows writing properly concurrent asynchronous code.

Btw, there is (do I need to say: was?) [GitHub - tc39/proposal-observable: Observables for ECMAScript](https://github.com/tc39/proposal-observable) which proposed a proper abstraction for push-based event sources.

---

_[View the full topic](https://es.discourse.group/t/event-async-await/1618)._
