封装一个promise类
作者:互联网
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);
}
}
})
}
}
})
}
标签:封装,一个,reject,value,promise,result,error,onRejected,HD 来源: https://blog.csdn.net/sinat_36048532/article/details/113064682