按照自己理解实现了下,不完美。。待填坑。all和race有问题
代码语言:javascript复制class MyPro {
constructor(func) {
this.state = "pending"; // or full or rejected
this.value = undefined;
this.tasks = [];
this.errortasks = [];
this.finnalytasks = [];
function resolve(value) {
if (this.state === "pending") {
this.value = value;
this.state = "full";
this._gg(this.value);
this
.tasks
.forEach(func => {
setTimeout(() => {
this.value = func(this.value)
})
});
} else {
return
}
}
function reject(reason) {
if (this.state === "pending") {
this.state = "rejected";
this
.errortasks
.forEach(func => {
setTimeout(() => {
if (typeof func === "function") {
func(reason)
}
})
});
} else {
return
}
}
try {
setTimeout(()=>func(resolve.bind(this), reject.bind(this)))
} catch (e) {
reject(e);
} finally {
setTimeout(() => {
this
.finnalytasks
.forEach(func => setTimeout(() => {
func()
}))
})
}
};
then(onFulfilled, onRejected) {
if (this.state === "pending") {
this
.tasks
.push(onFulfilled)
this
.errortasks
.push(onRejected)
}
return this;
};
catch (rejectFunc) {
if (this.state === "pending") {
this
.errortasks
.push(rejectFunc)
}
return this;
};
_gg(v){
//提供个观察者模式接口
}
static resolve(val){
return new MyPro((rel) =>rel(val))
}
static reject(){}
static race(arr){
return new MyPro((rel) =>{
//当某一个触发就触发
arr.forEach(item => {
item._gg = (v) => rel(v)
});
})
}
static all(arr){
let ps = arr.length;
const result = [];
return new MyPro((rel) =>{
arr.forEach(item => {
item._gg = (v) => {
}
})
rel(result);
})
}
}