Created
May 4, 2018 11:05
-
-
Save freddi301/2d101d29c443586e110c85fec9b59a09 to your computer and use it in GitHub Desktop.
TypeScript do notation using await
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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