const PENDING = 'pengding';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
class PromiseA {
private _data: any;
private _status: string;
private _onFulfilledCallbacks: Function[];
private _onRejectedCallbacks: Function[];
constructor(func: Function) {
this._data = null;
this._status = PENDING;
this._onFulfilledCallbacks = [];
this._onRejectedCallbacks = [];
try {
func(this._resolve.bind(this), this._reject.bind(this));
} catch (err) {
this._reject(err);
}
}
private _resolve(value: any): void | PromiseA {
process.nextTick(() => {
if (value instanceof PromiseA) {
return value.then(this._resolve.bind(this), this._reject.bind(this));
}
if (this._status !== PENDING) return;
this._status = FULFILLED;
this._data = value;
for (let cb of this._onFulfilledCallbacks) {
cb(this._data);
}
});
}
private _reject(reason: any): void {
process.nextTick(() => {
if (this._status !== PENDING) return;
this._status = REJECTED;
this._data = reason;
for (let cb of this._onRejectedCallbacks) {
cb(this._data);
}
});
}
public then(onFulfilled: Function, onRejected: Function): PromiseA {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : function (v) {return v}
onRejected = typeof onRejected === 'function
promise 浏览器实现的源码_基于Promises/A+规范实现的Promise源码(TypeScript版)
最新推荐文章于 2023-08-02 07:47:10 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)