听说现在的面试官喜欢让人手写实现Promise,我也来试试,先实现最基本的功能吧,以后空了再完善别的功能~
class MyPromise{
constructor(callback){
console.log('进入Mypromise的构造函数里')
this.state = 'pending';
this.result = '';
this.fulfillFun = null;
this.rejectFun = null;
let resolve = (val)=> {
console.log('进入resolve====',val)
if(this.state == 'pending') {
this.state = 'fulfilled';
this.result = val;
if(this.fulfillFun){
//针对resolve里还嵌套了定时器等异步操作,操作执行完自动调用then里的回调
this.fulfillFun();
this.fulfillFun = null;
}
}
}
let reject = (val)=>{
console.log('进入rejected',val)
if(this.state == 'pending') {
this.state = 'rejected';
this.result = val;
if(this.rejectFun){
this.rejectFun(this.result);
this.rejectFun = null;
}
}
}
try {
callback(resolve,reject)
}catch(e) {
reject(e)
}
}
then(onFulfilled, onRejected){
if(this.state === 'pending'){
this.fulfillFun = ()=>{
onFulfilled(this.result)
};
this.rejectFun = ()=>onRejected(this.result);
}
else if(this.state === 'fulfilled')
onFulfilled(this.result)
else {
onRejected(this.result)
}
}
catch(onRejected){
if(this.state === 'rejected')
onRejected(this.result)
}
static all(arr){
//空了再来写。。。
}
static resolve(onFulfilled){
return new MyPromise((r)=>{
r(onFulfilled)
})
}
}
//测试
let mypromise = new MyPromise((r,j)=>{
j('-------mypromise')
})
mypromise.then((m)=>console.log('mypromise.then:',m),
(m)=>console.log('mypromise.catch:',m));
let mypromise1 = new MyPromise((r,j)=>{
setTimeout(()=>{
j('计时器结合的mypromise1')
},100)
})
mypromise1.then((m)=>console.log('******mypromise1.then:',m),
(m)=>console.log('*******mypromise1.catch:',m));
let myRsolvePro = MyPromise.resolve('我是要变成promise的字符串')
myRsolvePro.then(m=>console.log('MyPromise.resolve.then:',m))