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.
This commit is contained in:
Ian Flanigan 2022-06-12 18:05:01 +02:00 committed by GitHub
parent 6f804758f1
commit d7cb6997d1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 3 deletions

View File

@ -13,7 +13,7 @@ import { Screen } from './Screen';
import { Drives } from './Drives';
import { Slinky } from './Slinky';
import { ThunderClock } from './ThunderClock';
import { noAwait, Ready } from './util/promises';
import { spawn, Ready } from './util/promises';
import styles from './css/Apple2.module.css';
@ -55,7 +55,7 @@ export const Apple2 = (props: Apple2Props) => {
...props,
};
const apple2 = new Apple2Impl(options);
noAwait((async () => {
spawn(async () => {
try {
await apple2.ready;
setApple2(apple2);
@ -67,7 +67,7 @@ export const Apple2 = (props: Apple2Props) => {
} catch (e) {
setError(e);
}
}))();
});
}
}, [props, drivesReady]);

View File

@ -11,6 +11,14 @@ export function noAwait<F extends (...args: unknown[]) => Promise<unknown>>(f: 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.