日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
TypeScriptPromise泛型

TypeScript 的 Promise 是一種用于處理異步操作的對(duì)象,Promise 可以用于表示一個(gè)尚未完成但預(yù)計(jì)在未來會(huì)完成的操作,例如網(wǎng)絡(luò)請(qǐng)求或文件讀寫。

在 TypeScript 中,可以使用泛型來定義 Promise,以使其更加靈活和通用,下面是一個(gè)使用泛型的 Promise 示例:

interface IPromise {
  then(onfulfilled?: (value: T) => IThenable, onrejected?: (reason: any) => IThenable): IPromise;
}
interface IThenable {
  (onfulfilled?: (value: T) => void, onrejected?: (reason: any) => void): void;
}
class MyPromise implements IPromise {
  private state: 'pending' | 'fulfilled' | 'rejected';
  private value: T | null;
  private reason: any | null;
  constructor(private execute: () => IPromiseExecutor) {}
  then(onfulfilled?: (value: T) => IThenable, onrejected?: (reason: any) => IThenable): IPromise {
    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;
  }
}

在這個(gè)示例中,我們首先定義了一個(gè) IPromise 接口,它包含一個(gè) then 方法,我們定義了一個(gè) IThenable 接口,它包含一個(gè)接受兩個(gè)參數(shù)(onfulfilledonrejected)的方法,我們創(chuàng)建了一個(gè)名為 MyPromise 的類,它實(shí)現(xiàn)了 IPromise 接口。

MyPromise 類中,我們定義了一個(gè)構(gòu)造函數(shù),它接受一個(gè)執(zhí)行器函數(shù)作為參數(shù),執(zhí)行器函數(shù)返回一個(gè)實(shí)現(xiàn)了 IPromiseExecutor 接口的對(duì)象,這個(gè)對(duì)象包含一個(gè) then 方法,用于處理成功和失敗的情況,當(dāng) Promise 的狀態(tài)變?yōu)?fulfilledrejected 時(shí),我們會(huì)調(diào)用執(zhí)行器函數(shù)的 then 方法,并將結(jié)果傳遞給回調(diào)函數(shù)。


標(biāo)題名稱:TypeScriptPromise泛型
本文網(wǎng)址:http://m.5511xx.com/article/dpsjocj.html