Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Last active October 18, 2017 04:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattpodwysocki/54540674352625f77a27f22e35aaee96 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/54540674352625f77a27f22e35aaee96 to your computer and use it in GitHub Desktop.
import { AsyncIterableX } from '../asynciterable';
import { AsyncSink } from '../asyncsink';
import { memoize } from './memoize';
export function asyncify<TSource>(
func: Function
): (...args: any[]) => AsyncIterableX<TSource> {
return function(...args: any[]) {
const sink = new AsyncSink<TSource>();
const handler = function(...innerArgs: any[]) {
sink.write(<any>innerArgs);
};
try {
func(...args.concat(handler));
} catch (e) {
sink.error(e);
}
return memoize(
(async function*() {
for (let next; !(next = await sink.next()).done; ) {
yield next.value;
}
sink.end();
})()
);
};
}
import { AsyncIterableX } from '../asynciterable';
import { AsyncSink } from '../asyncsink';
import { memoize } from './memoize';
export function asyncifyErrback<TSource>(
func: Function
): (...args: any[]) => AsyncIterableX<TSource> {
return function(...args: any[]) {
const sink = new AsyncSink<TSource>();
const handler = function(err: any, ...innerArgs: any[]) {
if (err) {
sink.error(err);
} else {
sink.write(<any>innerArgs);
}
};
try {
func(...args.concat(handler));
} catch (e) {
sink.error(e);
}
return memoize(
(async function*() {
for (let next; !(next = await sink.next()).done; ) {
yield next.value;
}
sink.end();
})()
);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment