Last active
December 30, 2022 02:55
-
-
Save spence/759784432f9cb733254cfba4f45bd7f1 to your computer and use it in GitHub Desktop.
Bind event stream into for-await-of
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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