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