// 定义一个简单的Promise
class SimplePromise<T> {
private _state: 'pending' | 'resolved' | 'rejected' = 'pending';
private _value: T | undefined;
private _reason: any | undefined;
private _onResolveCallbacks: Array<(value: T) => void> = [];
private _onRejectCallbacks: Array<(reason: any) => void> = [];
// 构造函数接收一个函数,该函数接收两个函数参数resolve和reject
constructor(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) {
executor(this.resolve.bind(this), this.reject.bind(this));
}
// 使实例可被调用,类似于then方法
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): SimplePromise<TResult1 | TResult2> {
let promise2 = new SimplePromise<TResult1 | TResult2>((resolve, reject) => {
if (this._state === 'pending') {
this._onResolveCallbacks.push(value => {
try {
let result = onfulfilled ? onfulfilled(value) : value;
resolve(result);
} catch (e) {
reject(e);
}
});
this._onRejectCallbacks.push(reason => {
try {
let result = onrejected ? onrejected(reason) : reason;
resolve(result);
} catch (e) {
reject(e);
}
});
} else if (this._state === 'resolved') {
try {
let result = onfulfilled ? onfulfilled(this._value) : this._value;
resolve(result);
} catch (e) {
reject(e);
}
} else {
try {
let result = onrejected ? onrejected(this._reason) : this._reason;
resolve(result);
} catch (e) {
reject(e);
}
}
});
return promise2;
}
// 设置Promise为resolved状态
private resolve(value: T | PromiseLike<T>) {
const resolve = (value: T) => {
if (this._state === 'pending') {
this._state = 'resolved';
this
评论已关闭