Skip to content

Instantly share code, notes, and snippets.

@spion
Last active June 24, 2019 12:34
Show Gist options
  • Save spion/28ca1b23cf35fa44adb4ae18e00d6ba7 to your computer and use it in GitHub Desktop.
Save spion/28ca1b23cf35fa44adb4ae18e00d6ba7 to your computer and use it in GitHub Desktop.
type PromiseState<T> = {
state: 'fulfilled', value: T
} | {state: 'pending'} | {state: 'rejected', error: Error};
let wm = new WeakMap<Promise<any>, PromiseState<any>>()
export function asyncCase<T, U>(promise: Promise<T>, handlers: {
pending?: () => U;
fulfilled?: (t: T) => U;
rejected?: (e: any) => U;
}) {
if (!wm.has(promise)) {
let fp = observable({state: 'pending', value: null, error: null});
wm.set(promise, fp);
promise.then(
val => Object.assign(fp, {state: 'fulfilled', value: val}),
err => Object.assign(fp, {state: 'rejected', error: err}));
}
let promiseData = wm.get(promise) as PromiseState<T>
switch (promiseData.state) {
case 'pending':
return handlers.pending && handlers.pending()
case 'rejected':
return handlers.rejected && handlers.rejected(promiseData.error)
case 'fulfilled':
return handlers.fulfilled && handlers.fulfilled(promiseData.value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment