Skip to content

Instantly share code, notes, and snippets.

@spence
Last active December 30, 2022 02:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spence/759784432f9cb733254cfba4f45bd7f1 to your computer and use it in GitHub Desktop.
Save spence/759784432f9cb733254cfba4f45bd7f1 to your computer and use it in GitHub Desktop.
Bind event stream into for-await-of
const stream = new class { // Mock event stream
handler = null;
async start() {
while (true) {
const ms = Math.random() * 100;
await new Promise(resolve => setTimeout(resolve, ms));
if (this.handler) this.handler(ms);
if (ms < 10 && this.handler) this.handler(ms);
}
}
onEvent(handler) {
this.handler = handler;
}
}
class Monitor {
events = []; // store events
resolve = () => {}; // resolves current outstanding promise
constructor(handler) {
handler(event => { // binds event listener
this.events.push(event); // add event
this.resolve(); // call resolve
});
}
async *stream() { // generator
while (true) {
let event;
while (event = this.events.shift()) // get and remove previous event
yield event; // yield event
await new Promise(r => this.resolve = r); // wait for next call to handler
}
}
}
// Bind event stream into monitor
const monitor = new Monitor(stream.onEvent.bind(stream));
stream.start();
// Stream events
for await (const event of monitor.stream()) {
console.log('monitor', { event })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment