众所周知promise是一个解决异步编程,也就是回调地狱的解决方案,他有三种状态:1.resolve(已成功),2.reject(已失败),3.pendding(进行中)。
那他是怎么用的呢?
let p = new Promise((resolve,reject) => {
setTimeout(() => {
resolve(123);
reject(456);
},1000)
})
p.then(res => {
console.log(res);
}).catch(err => {
console.log(err);
})
然后咱们就用原生方法去实现一个promise
class MyPromise{
constructor(callback){
this.status = 'pendding';
this.result = null;
this.err = null;
this.resolveFn = null;
this.rejectFn = null;
this.resolve = function(val){
if(this.status === 'pendding'){
this.status = 'resolve';
this.result = val;
this.resolveFn && this.resolveFn(this.result);
}
}
this.reject = function(err){
if(this.status === 'pendding'){
this.status = 'reject';
this.err = err;
this.rejectFn && this.rejectFn(this.err);
}
}
callback(this.resolve.bind(this),this.reject.bind(this));
}
then(callback){
if(this.status === 'resolve' ){
callback(this.result);
}else{
this.resolveFn = callback;
}
return this;
}
catch(callback){
if(this.status === 'reject' ){
callback(this.err);
}else{
this.rejectFn = callback;
}
}
}
现在去用一下:
let p = new MyPromise((resolve,reject) => {
setTimeout(() => {
resolve(123);
reject(456);
},1000)
})
p.then(res => {
console.log(res);
}).catch(err => {
console.log(err);
})
结果请自行打印。此方法我已试验,暂无问题,欢迎来怼!