Skip to content

Instantly share code, notes, and snippets.

@jelcaf
Created July 17, 2020 12:23
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 jelcaf/883b01633a599d870788dad5771d39e0 to your computer and use it in GitHub Desktop.
Save jelcaf/883b01633a599d870788dad5771d39e0 to your computer and use it in GitHub Desktop.
EventEmitter to Generator
import pauseable from 'pauseable';
import EventEmitter from 'events';
function iter(em) {
pauseable.resume(em);
return new Promise((resolve) => {
em.once('foo', (data) => {
pauseable.pause(em);
resolve(data);
});
});
}
function * gen (em) {
while (true) {
yield iter(em);
}
}
async function start() {
const emitter = new EventEmitter();
const ws = new WebSocket('wss://stream.binance.com:9443/ws/etcbtc@aggTrade');
ws.onmessage = ({ data }) => emitter.emit('foo', data);
for (const data of gen(emitter)) {
console.log(await data);
}
}
start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment