TypeScript Promise泛型
- 行业动态
- 2024-04-15
- 3644
TypeScript 的 Promise 是一种用于处理异步操作的对象,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 接口,它包含一个接受两个参数(onfulfilled 和 onrejected)的方法,我们创建了一个名为 MyPromise 的类,它实现了 IPromise 接口。
在 MyPromise 类中,我们定义了一个构造函数,它接受一个执行器函数作为参数,执行器函数返回一个实现了 IPromiseExecutor 接口的对象,这个对象包含一个 then 方法,用于处理成功和失败的情况,当 Promise 的状态变为 fulfilled 或 rejected 时,我们会调用执行器函数的 then 方法,并将结果传递给回调函数。
本站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本站,有问题联系侵删!
本文链接:http://www.xixizhuji.com/fuzhu/290403.html