Socket
Socket
Sign inDemoInstall

event-target-to-async-iter

Package Overview
Dependencies
0
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    event-target-to-async-iter

Takes an event target and an event name and turns it into an async iterable


Version published
Weekly downloads
5
increased by66.67%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

EventTarget to Async Iterable

Takes an EventTarget and an event name and turns it into an async iterable.

Note that the async iterable will not complete until either

  • an abort controller aborts it,
  • the return function is called, or
  • a returnEvent is provided and gets dispatched on the event target.

Example 1

Waiting for web socket messages:

const socket = new WebSocket('wss://example.com/socketserver');

const iter = eventTargetToAsyncIter(socket, 'message', { 
  returnEvent: 'close'
});

for await (const message of iter) {
  console.log(message)
}

Example 2

Say you have a heavily callback-based API such as HTMLRewriter and would prefer to process it as an async iterable. You can use a custom event target and eventTargetToAsyncIter:

const target = new EventTarget();
const iter = eventTargetToAsyncIter(target, 'data');

// Helper function that consumes a readable stream
async function swallow(stream) {
  const reader = stream.getReader();
  while (await reader.read().then(x => !x.done)) {}
}

const response = new HTMLRewriter()
  .on('.athing[id]', {
    element(el) {
      target.dispatchEvent(new CustomEvent('data', { 
        detail: el.getAttribute('id'),
      }));
    }
  })
  .transform(await fetch('https://news.ycombinator.com'));

// No await here
swallow(response.body)
  .then(() => iter.return()) // Don't create an endless loop
  .catch(e => iter.throw(e)) // Don't swallow errors

for await (const event of iter) {
  const id = Number(event.detail);
  console.log(id);
}

FAQs

Last updated on 08 Feb 2022

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc