class MyPromise{
private state:string = 'pending';
private resolveFn:(res) => void;
private rejectFn:(error) => void;
private res:any = null;
private error:any = null;
constructor(fn:(r,j) => void){
this.resolve = this.resolve.bind(this)
this.reject = this.reject.bind(this)
fn(this.resolve,this.reject)
}
private resolve(res){
this.state = 'resolve';
this.res = res;
if(this.resolveFn){
this.resolveFn(res);
}
}
private reject(error){
this.state = 'reject';
this.error = error;
if(this.rejectFn){
this.rejectFn(error);
}
}
public then(fn:(res) => void):MyPromise{
if(this.state == 'resolve'){
fn(this.res)
}else if(this.state == 'pending'){
this.resolveFn = fn;
}
return this;
}
public catch(fn:(error) => void):MyPromise{
if(this.state == 'reject'){
fn(this.error)
}else if(this.state == 'pending'){
this.rejectFn = fn;
}
return this;
}
static all(fnArray:Array<() => any>){
}
}
调用方法
new MyPromise((r,j) => {
setTimeout(() => {
j('@');
}, 1000);
}).then(res => {
console.log(res,'@')
}).catch(error => {
console.log(error,'!')
})
我建了一个前端微信交流群,欢迎大家加入,qq中转群号:1076484243
网友评论