-
-
Save rbuckton/c0f4817d2c1d66aef5a9ee3dee7cbee3 to your computer and use it in GitHub Desktop.
Reimagining events as async iterables
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
const EventEmitter = require('events').EventEmitter; | |
const fromEventPattern = require('ix/asynciterable/fromeventpattern').fromEventPattern; | |
// Get Async Iterable | |
const e = new EventEmitter(); | |
const ai = fromEventPattern( | |
h => e.addListener('data', h), | |
h => e.removeListener('data', h) | |
); | |
// Emit some data | |
e.emit('data', 'foo'); | |
e.emit('data', 'bar'); | |
e.emit('data', 'baz'); | |
// Get some data back out | |
let result = await ai.next(); | |
console.log(result.value); // 'foo' | |
result = await ai.next(); | |
console.log(result.value); // 'bar' | |
result = await ai.next(); | |
console.log(result.value); // 'baz' | |
// Close it off | |
await ai.return(); |
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
'use strict'; | |
import { AsyncSink } from '../asyncsink'; | |
import { memoize } from './memoize'; | |
export function fromEventPattern<TSource>( | |
addHandler: (handler: Function) => void, | |
removeHandler: (handler: Function) => void): AsyncIterableIterable<TSource> { | |
const sink = new AsyncSink<TSource>(); | |
const handler = function (e: TSource) { | |
sink.write(e); | |
}; | |
addHandler(handler); | |
const it = memoize({ | |
next() { | |
return sink.next(); | |
}, | |
return() { | |
removeHandler(handler); | |
sink.end(); | |
return Promise.resolve({ done: true } as IteratorResult<TSource>); | |
}, | |
[Symbol.asyncIterator]() { | |
return it; | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment