Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ea8335f
commit 83c75a9
Showing
2 changed files
with
74 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
const defer = require('../defer') | ||
|
||
async function* fromEvent(eventName, emitter) { | ||
let queue = [defer()] | ||
|
||
emitter.on(eventName, (...args) => { | ||
const [_, resolve] = queue[queue.length - 1] | ||
resolve(...args) | ||
queue.push(defer()) | ||
}) | ||
|
||
while (true) { | ||
const promise = queue[0][0] | ||
yield await promise | ||
queue.shift() | ||
} | ||
} | ||
|
||
module.exports = fromEvent |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
const EventEmitter = require('events') | ||
const fromEvent = require('.') | ||
const take = require('../take') | ||
const compose = require('../compose') | ||
|
||
class MyEmitter extends EventEmitter {} | ||
const emitter = new MyEmitter() | ||
|
||
it('returns a generator that generates a new value for every listened event', async () => { | ||
const gen = take(2, fromEvent('foo', emitter)) | ||
const output = [] | ||
|
||
async function emitEvents() { | ||
return new Promise((resolve) => { | ||
emitter.emit('foo', 1) | ||
emitter.emit('foo', 2) | ||
emitter.emit('foo', 3) | ||
resolve() | ||
}) | ||
} | ||
|
||
async function consumeEvents() { | ||
for await (let event of gen) { | ||
output.push(event) | ||
} | ||
} | ||
|
||
await Promise.all([consumeEvents(), emitEvents()]) | ||
|
||
expect(output).toEqual([1, 2]) | ||
}) | ||
|
||
it('is composable', async () => { | ||
const gen = compose(fromEvent('foo', emitter), take(2)) | ||
const output = [] | ||
|
||
async function emitEvents() { | ||
return new Promise((resolve) => { | ||
emitter.emit('foo', 1) | ||
emitter.emit('foo', 2) | ||
emitter.emit('foo', 3) | ||
resolve() | ||
}) | ||
} | ||
|
||
async function consumeEvents() { | ||
for await (let event of gen) { | ||
output.push(event) | ||
} | ||
} | ||
|
||
await Promise.all([consumeEvents(), emitEvents()]) | ||
|
||
expect(output).toEqual([1, 2]) | ||
}) |