class HD {
static PENDING = "pending";
static FULFILLED = "fulfilled";
static REJECTED = "rejected";
constructor(executor) {
this.status = HD.PENDING;
this.value = null;
this.callbacks = [];
try {
executor(this.resolve.bind(this), this.reject.bind(this));
} catch (error) {
this.reject(error);
}
}
resolve(value){
if(this.status == HD.PENDING) {
this.status = HD.FULFILLED;
this.value = value;
setTimeout(() => {
this.callbacks.map(callback => {
callback.onFulfilled(value);
});
});
}
}
reject(value){
if(this.status == HD.PENDING){
this.status = HD.REJECTED;
this.value = value;
setTimeout(() => {
this.callbacks.map(callback => {
callback.onRejected(value);
})
})
}
}
then(onFulfilled, onRejected){
if(typeof onFulfilled != "function"){
onFulfilled = value => value;
}
if(typeof onRejected != "function"){
onRejected = value => value;
}
return new HD((resolve, reject) => {
if(this.status == HD.FULFILLED){
setTimeout(() => {
try {
let result = onFulfilled(this.value);
if(result instanceof HD){
result.then(resolve, reject);
} else {
resolve(result);
}
} catch (error) {
//onRejected(error);
reject(error);
}
})
}
if(this.staus == HD.REJECTED) {
setTimeout(() => {
try(
let result = onRejected(this.value);
if (result instanceof HD){
result.then(resolve, reject);
} else {
resolve(result);
}
) catch (error) {
//onRejected(error)
reject(error);
}
})
}
if(this.status == HD.PENDING) {
this.callbacks.push({
onFulfilled: value => {
try {
onFulfilled(value);
} catch (error) {
onRejected(error);
}
},
onRejected: value => {
try {
onRejected(value);
} catch (error) {
onRejected(error);
}
}
})
}
}
})
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。