UNPKG

1.14 kBJavaScriptView Raw
1import { AsyncSink } from './asyncsink';
2import { memoize } from './operators/memoize';
3/**
4 * Converts the callback function into wrapped function which returns an async-iterable.
5 *
6 * @export
7 * @template TSource The type of the value returned from the callback.
8 * @param {Function} func The callback function to wrap as an async-iterable.
9 * @returns {(...args: any[]) => AsyncIterableX<TSource>} A function when invoked, returns an async-iterable from the callback.
10 */
11export function asyncify(func) {
12 return function (...args) {
13 const sink = new AsyncSink();
14 const handler = function (...innerArgs) {
15 sink.write(innerArgs.length === 1 ? innerArgs[0] : innerArgs);
16 sink.end();
17 };
18 try {
19 func(...args.concat(handler));
20 }
21 catch (e) {
22 sink.error(e);
23 sink.end();
24 }
25 const yielder = async function* () {
26 for (let next; !(next = await sink.next()).done;) {
27 yield next.value;
28 }
29 };
30 return memoize()(yielder());
31 };
32}
33
34//# sourceMappingURL=asyncify.mjs.map