首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >TypeScript中的Awaitable类型

TypeScript中的Awaitable类型
EN

Stack Overflow用户
提问于 2019-05-07 11:27:49
回答 2查看 3.9K关注 0票数 6

我在JavaScript中经常使用异步/等待。现在,我正在逐步将代码基的某些部分转换为TypeScript。

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

代码语言:javascript
运行
复制
type Awaitable<T> = T | Promise<T>;

async function increment(getNumber: () => Awaitable<number>): Promise<number> {
  const num = await getNumber();
  return num + 1;
}

它可以这样称呼:

代码语言:javascript
运行
复制
// logs 43
increment(() => 42).then(result => {console.log(result)})

// logs 43
increment(() => Promise.resolve(42)).then(result => {console.log(result)})

这个很管用。但是,必须为我使用异步/等待和Awaitable的所有项目指定TypeScript是件很烦人的事。

我真不敢相信这样的类型不是天生的,但我却找不到。TypeScript有内置型吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-14 11:37:48

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

例如,在lib.es5.d.tslib.es2015.promise.d.ts中,他们将T | PromiseLike<T>用于您的Awaitable<T>可能具有意义的不同地方:

代码语言:javascript
运行
复制
/**
 * 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>;
}

lib.es5.d.ts中,没有什么比您的lib.es5.d.ts更能定义PromiseLikePromise了。

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

附带注意:基于这些定义,在您的PromiseLike中使用Promise而不是Promise可能是有意义的。

代码语言:javascript
运行
复制
type Awaitable<T> = T | PromiseLike<T>;
票数 5
EN

Stack Overflow用户

发布于 2019-05-07 11:34:47

  1. async/await总是会导致语句被包装成一个承诺,所以您的函数总是返回一个允诺。
  2. 一切都可以等待,不管是异步的还是非异步的,所以定制的Awaitable类型可能只是多余的.
代码语言:javascript
运行
复制
async function test() {
    const foo = await 5;
    console.log(foo);

    const bar = await 'Hello World';
    console.log(bar);

    const foobar = await Promise.resolve('really async');
    console.log(foobar);
}

test();

链接到ts操场

您不需要额外输入imho,因为您的函数总是有:

代码语言:javascript
运行
复制
async function foo<T>(task: () => T | Promise<T>): Promise<T> {
  const result = await task();

  return result;
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56021581

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档