Skip to content

Instantly share code, notes, and snippets.

@freddi301
Created May 4, 2018 11:05
Show Gist options
  • Save freddi301/2d101d29c443586e110c85fec9b59a09 to your computer and use it in GitHub Desktop.
Save freddi301/2d101d29c443586e110c85fec9b59a09 to your computer and use it in GitHub Desktop.
TypeScript do notation using await
class Nothing<T> implements PromiseLike<T> {
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2> {
return (onrejected as any)(this);
}
}
class Just<T> implements PromiseLike<T> {
constructor(private value: T) { }
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2> {
return (onfulfilled as any)(this.value);
}
}
type Maybe<T> = Nothing<T> | Just<T>
const nothing = <T>(): Nothing<T> => new Nothing;
const just = <T>(value: T): Just<T> => new Just(value)
async function hu() {
console.log(await just(5) + await just(4));
try { console.log(await nothing<number>() + await just(4)); }
catch (e) { console.error("XD") }
return await just(5) + await just(5);
}
async function logit(promise) {
try { console.info(await promise); }
catch (e) { console.error(e); }
}
logit(hu());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment