Skip to content

Instantly share code, notes, and snippets.

@rbuckton
Forked from mattpodwysocki/example.ts
Last active June 15, 2017 22:32
Show Gist options
  • Save rbuckton/c0f4817d2c1d66aef5a9ee3dee7cbee3 to your computer and use it in GitHub Desktop.
Save rbuckton/c0f4817d2c1d66aef5a9ee3dee7cbee3 to your computer and use it in GitHub Desktop.
Reimagining events as async iterables
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();
'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