Created
July 17, 2020 12:23
-
-
Save jelcaf/883b01633a599d870788dad5771d39e0 to your computer and use it in GitHub Desktop.
EventEmitter to Generator
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
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