|
| 1 | +import { deferGenerator } from 'inside-out-async' |
| 2 | + |
| 3 | +export interface CallbackIterable<T> extends AsyncIterable<T> { |
| 4 | + yield(data: T): void |
| 5 | + end(): void |
| 6 | +} |
| 7 | + |
| 8 | +/** |
| 9 | + * Returns an iterable with methods to help turn event emitters or callbacks into async iterables. |
| 10 | +
|
| 11 | +This leverages the [`inside-out-async`](https://www.npmjs.com/package/inside-out-async#deferGenerator) package which can be used directly if you want something similar for generators. (It is bundled so it's not a dependency.) |
| 12 | +
|
| 13 | +It adds two methods to the returned iterable. |
| 14 | +
|
| 15 | +- `itr.yield(data: T): void` queues data to be read |
| 16 | +- `itr.end(): void` ends the iterable |
| 17 | +
|
| 18 | +And will buffer *all* data given to `yield()` until it's read. |
| 19 | +
|
| 20 | +```ts |
| 21 | +import { fromCallback } from 'streaming-iterables' |
| 22 | +
|
| 23 | +const pokeLog = fromCallback() |
| 24 | +itr.yield('Charmander') |
| 25 | +itr.yield('Ash') |
| 26 | +itr.yield('Pokeball') |
| 27 | +itr.end() |
| 28 | +
|
| 29 | +for await (const pokeData of pokeLog) { |
| 30 | + console.log(pokeData) // Charmander, Ash, Pokeball |
| 31 | +} |
| 32 | +
|
| 33 | +// To use it as a callback |
| 34 | +const emitter = new EventEmitter() |
| 35 | +const consoles = fromCallback() |
| 36 | +emitter.on('data', consoles.yield) |
| 37 | +emitter.on('close', consoles.end) |
| 38 | +
|
| 39 | +emitter.emit('data', 'nintendo') |
| 40 | +emitter.emit('data', 'sony') |
| 41 | +emitter.emit('data', 'sega') |
| 42 | +emitter.emit('close') |
| 43 | +
|
| 44 | +for await (const console of consoles) { |
| 45 | + console.log(console) // 'nintendo', 'sony', 'sega' |
| 46 | +} |
| 47 | +
|
| 48 | +``` |
| 49 | + */ |
| 50 | +export function fromCallback<T>(): CallbackIterable<T> { |
| 51 | + const { generator, queueValue, queueReturn } = deferGenerator<T, T, undefined>() |
| 52 | + |
| 53 | + const cbIterable: CallbackIterable<T> = { |
| 54 | + ...generator, |
| 55 | + yield: queueValue, |
| 56 | + end: () => queueReturn() |
| 57 | + } |
| 58 | + return cbIterable |
| 59 | +} |
0 commit comments