Skip to content

Instantly share code, notes, and snippets.

@spion spion/async-case.ts
Last active Jun 24, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.