apple2js/js/components/util/promises.ts
Ian Flanigan d7cb6997d1
Add spawn as a way of calling promise-returning blocks (#131)
This change adds `spawn` which takes a no-argument, promise-returning
function, calls it, and returns `void`.  This makes it easy to call
async blocks from `useEffect` and other places that don't take async
functions, but also makes such calls explicit.
2022-06-12 09:05:01 -07:00

40 lines
1.1 KiB
TypeScript

/**
* Converts a function type returning a `Promise` to a function type returning `void`.
*/
export type NoAwait<F extends (...args: unknown[]) => Promise<unknown>> =
(...args: Parameters<F>) => void;
/**
* Signals that the argument returns a `Promise` that is intentionally not being awaited.
*/
export function noAwait<F extends (...args: unknown[]) => Promise<unknown>>(f: F): NoAwait<F> {
return f as NoAwait<F>;
}
/**
* Calls the given `Promise`-returning function and returns void, signalling that it is
* explicitly not awaited.
*/
export function spawn(f: () => Promise<unknown>): void {
noAwait(f)();
}
/**
* Utility class that allows a promise to be passed to a
* service to be resolved.
*/
export class Ready {
onError: (value?: unknown) => void;
onReady: (value?: unknown) => void;
ready: Promise<unknown>;
constructor(private errorHandler = console.error) {
this.ready = new Promise((resolve, reject) => {
this.onReady = resolve;
this.onError = reject;
}).catch(this.errorHandler);
}
}