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

在 TypeScript 中,可以使用泛型來定義 Promise,以使其更加靈活和通用,下面是一個使用泛型的 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; } }
在這個示例中,我們首先定義了一個 IPromise 接口,它包含一個 then 方法,我們定義了一個 IThenable 接口,它包含一個接受兩個參數(shù)(onfulfilled 和 onrejected)的方法,我們創(chuàng)建了一個名為 MyPromise 的類,它實現(xiàn)了 IPromise 接口。
在 MyPromise 類中,我們定義了一個構(gòu)造函數(shù),它接受一個執(zhí)行器函數(shù)作為參數(shù),執(zhí)行器函數(shù)返回一個實現(xiàn)了 IPromiseExecutor 接口的對象,這個對象包含一個 then 方法,用于處理成功和失敗的情況,當(dāng) Promise 的狀態(tài)變?yōu)?fulfilled 或 rejected 時,我們會調(diào)用執(zhí)行器函數(shù)的 then 方法,并將結(jié)果傳遞給回調(diào)函數(shù)。
網(wǎng)頁名稱:TypeScriptPromise泛型
當(dāng)前URL:http://www.dlmjj.cn/article/dpsjocj.html


咨詢
建站咨詢
