TypeScript 中的可等待类型

Rem*_*ing 7 async-await typescript

我在 JavaScript 中经常使用 async/await。现在我\xe2\x80\x99m逐渐将我的代码库的某些部分转换为TypeScript。

\n\n

在某些情况下,我的函数接受将被调用和等待的函数。这意味着它可以返回一个承诺,只是一个同步值。我已经Awaitable为此定义了类型。

\n\n
type Awaitable<T> = T | Promise<T>;\n\nasync function increment(getNumber: () => Awaitable<number>): Promise<number> {\n  const num = await getNumber();\n  return num + 1;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

可以这样调用:

\n\n
// logs 43\nincrement(() => 42).then(result => {console.log(result)})\n\n// logs 43\nincrement(() => Promise.resolve(42)).then(result => {console.log(result)})\n
Run Code Online (Sandbox Code Playgroud)\n\n

这有效。Awaitable然而,必须为我所有使用 async/await 和 TypeScript 的项目进行指定是很烦人的。

\n\n

我可以\xe2\x80\x99t真的相信这样的类型是\xe2\x80\x99t内置的,但我无法\xe2\x80\x99t找到一个。TypeScript 有内置的可等待类型吗?

\n

T.J*_*der 5

我相信这个问题的答案是:不,没有内置类型。

lib.es5.d.ts和中lib.es2015.promise.d.ts,它们用于T | PromiseLike<T>您认为有意义的各个地方Awaitable<T>,例如:

/**
 * Represents the completion of an asynchronous operation
 */
interface Promise<T> {
    /**
     * Attaches callbacks for the resolution and/or rejection of the Promise.
     * @param onfulfilled The callback to execute when the Promise is resolved.
     * @param onrejected The callback to execute when the Promise is rejected.
     * @returns A Promise for the completion of which ever callback is executed.
     */
    then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;

    /**
     * Attaches a callback for only the rejection of the Promise.
     * @param onrejected The callback to execute when the Promise is rejected.
     * @returns A Promise for the completion of the callback.
     */
    catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}
Run Code Online (Sandbox Code Playgroud)

他们定义和 的Awaitable地方与您的不同。lib.es5.d.tsPromiseLikePromise

我认为如果他们定义了一个,他们会在这些定义中使用它。

旁注:根据这些定义,使用PromiseLike而不是Promise在您的Awaitable

type Awaitable<T> = T | PromiseLike<T>;
Run Code Online (Sandbox Code Playgroud)