class P {
static pedding = 'pedding';
static fulfilled = 'fulfilled';
static rejected = 'rejected';
constructor(fn) {
this.status = P.pedding;
this.result = null;
this.successCallback = [];
this.failedCallback = [];
try {
fn(this.resolve.bind(this), this.reject.bind(this));
}
catch (error) {
this.reject(error);
}
}
resolve(result) {
setTimeout(() => {
if (this.status === P.pedding) {
this.status = P.fulfilled;
this.result = result;
this.successCallback.forEach(callback => {
callback(result);
});
}
});
}
reject(result) {
setTimeout(() => {
if (this.status === P.pedding) {
this.status = P.rejected;
this.result = result;
this.failedCallback.forEach(callback => {
callback(result);
});
}
});
}
then(onSuccess, onFailed) {
return new P((resolve, reject) => {
onSuccess = typeof onSuccess === 'function' ? onSuccess : () => {};
onFailed = typeof onFailed === 'function' ? onFailed : () => {};
if (this.status === P.pedding) {
this.successCallback.push(onSuccess);
this.failedCallback.push(onFailed);
}
if (this.status === P.fulfilled) {
setTimeout(() => {
onSuccess(this.result);
});
}
if (this.status === P.rejected) {
setTimeout(() => {
onFailed(this.result);
});
}
});
}
}