TypeScript Promise泛型

TypeScript 的 Promise 是一种用于处理异步操作的对象,Promise 可以用于表示一个尚未完成但预计在未来会完成的操作,例如网络请求或文件读写。

TypeScript Promise泛型
(图片来源网络,侵删)

在 TypeScript 中,可以使用泛型来定义 Promise,以使其更加灵活和通用,下面是一个使用泛型的 Promise 示例:

interface IPromise<T> {
  then<U>(onfulfilled?: (value: T) => IThenable<U>, onrejected?: (reason: any) => IThenable<U>): IPromise<U>;
}
interface IThenable<T> {
  (onfulfilled?: (value: T) => void, onrejected?: (reason: any) => void): void;
}
class MyPromise<T> implements IPromise<T> {
  private state: 'pending' | 'fulfilled' | 'rejected';
  private value: T | null;
  private reason: any | null;
  constructor(private execute: () => IPromiseExecutor<T>) {}
  then<U>(onfulfilled?: (value: T) => IThenable<U>, onrejected?: (reason: any) => IThenable<U>): IPromise<U> {
    const promise = new MyPromise((resolve, reject) => {
      this.execute().then(
        result => {
          if (this.state === 'pending') {
            this.state = 'fulfilled';
            this.value = result;
            const thenable = onfulfilled ? onfulfilled(result) : result;
            if (typeof thenable === 'function') {
              thenable(resolve, reject);
            } else {
              resolve(thenable as U);
            }
          }
        },
        reason => {
          if (this.state === 'pending') {
            this.state = 'rejected';
            this.reason = reason;
            const thenable = onrejected ? onrejected(reason) : reason;
            if (typeof thenable === 'function') {
              thenable(resolve, reject);
            } else {
              reject(thenable as U);
            }
          }
        }
      );
    });
    return promise;
  }
}

在这个示例中,我们首先定义了一个 IPromise 接口,它包含一个 then 方法,我们定义了一个 IThenable 接口,它包含一个接受两个参数(onfulfilledonrejected)的方法,我们创建了一个名为 MyPromise 的类,它实现了 IPromise 接口。

MyPromise 类中,我们定义了一个构造函数,它接受一个执行器函数作为参数,执行器函数返回一个实现了 IPromiseExecutor 接口的对象,这个对象包含一个 then 方法,用于处理成功和失败的情况,当 Promise 的状态变为 fulfilledrejected 时,我们会调用执行器函数的 then 方法,并将结果传递给回调函数。

原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/477545.html

(0)
未希新媒体运营
上一篇 2024-04-15 08:12
下一篇 2024-04-15 08:13

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

云产品限时秒杀。精选云产品高防服务器,20M大带宽限量抢购  >>点击进入