基于 Promise A+ 规范使用Typescript实现Promise
以下是一个简单的基于Promise/A+规范的Typescript实现的示例:
interface IPromise<T> {
then<U>(onFulfilled?: (value: T) => U | IPromise<U>, onRejected?: (error: any) => U | IPromise<U>): IPromise<U>;
catch<U>(onRejected?: (error: any) => U | IPromise<U>): IPromise<U>;
}
class MyPromise<T> implements IPromise<T> {
private state: 'pending' | 'fulfilled' | 'rejected' = 'pending';
private value: T | undefined;
private reason: any;
private onFulfilledCallbacks: Array<(value: T) => void> = [];
private onRejectedCallbacks: Array<(reason: any) => void> = [];
constructor(executor: (resolve: (value?: T | IPromise<T>) => void, reject: (reason?: any) => void) => void) {
executor(this.resolve.bind(this), this.reject.bind(this));
}
private resolve(value?: T | IPromise<T>) {
if (this.state === 'pending') {
if (value instanceof MyPromise) {
value.then(this.resolve.bind(this), this.reject.bind(this));
} else {
this.state = 'fulfilled';
this.value = value as T;
this.onFulfilledCallbacks.forEach(callback => callback(this.value));
}
}
}
private reject(reason?: any) {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
this.onRejectedCallbacks.forEach(callback => callback(this.reason));
}
}
then<U>(onFulfilled?: (value: T) => U | IPromise<U>, onRejected?: (error: any) => U | IPromise<U>): IPromise<U> {
let promise2 = new MyPromise<U>((resolve, reject) => {
if (this.state === 'fulfilled') {
let x = onFulfilled ? onFulfilled(this.value as T) : this.value as U;
resolve(x);
} else if (this.state === 'rejected') {
let x = onRejected ? onRejected(this.reason) : this.reason;
reject(x);
} else {
this.onFulfilledCallbacks.push(() => {
let x = onFulfilled ? onFulfilled(this.value as T) : this.value as U;
resolve(x);
});
this.onRejectedCallbacks.push(() => {
let x = onRejected ? onRejected(this.reason) : this.reason;
reject(x);
});
}
});
r
评论已关闭