typescript TypeScript使用await表示法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript TypeScript使用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());

以上是关于typescript TypeScript使用await表示法的主要内容,如果未能解决你的问题,请参考以下文章