UNPKG

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