es6 promise实现

promise日常用法

new Promise((resolve, reject) => {
            //异步成功执行resolve,否则执行reject

        }).then((res) => {
            //resolve触发第一个回调函数执行
        }, (err) => {
            // reject 触发第二个回调函数执行

        }).then(res => {
            //需要保证then方法返回的依然是promise
            //这样才可以实现链式调用
        }).catch(reason => {

        })

Promise.all([promise1, ...]).then();

我们要实现promise状态,和.then()方法

基础版promise

  1. promise状态:pending(未完成)、fulfilled(完成)、rejected(拒绝)
    我们再new Promise时默认状态为pending,然后在处理回调时为fulfilled(完成)或者rejected(拒绝)。执行改变状态后不再执行另一个方法
class Promise {
     constructor(excutorCallBack) {
         this.status = 'pending';
         let resolveFn = result => {
             if (this.status !== 'pending') return;
              let timer = setTimeout(() => {
                 this.status = 'fulfilled';
             }, 0);
         }
         let rejectFn = reason => {
             if (this.status !== 'pending') return;
              let timer = setTimeout(() => {
                 this.status = 'rejected';
             }, 0);
         }
         try {
             excutorCallBack(resolveFn, rejectFn);
         } catch (err) {
             rejectFn(err)
         }
     }
  }
  1. 实现.then() 方法
 class Promise {
     constructor(excutorCallBack) {
         this.status = 'pending';
         this.value = undefined;
         this.fulfillAry = [];
         this.rejectedAry = [];
        
         let resolveFn = result => {
             if (this.status !== 'pending') return;
             let timer = setTimeout(() => {
                 this.status = 'fulfilled';
                 this.value = result;
                 this.fulfillAry.forEach(item => {
                     item(this.value)
                 })
             }, 0);
         }
         let rejectFn = reason => {
             if (this.status !== 'pending') return;
             let timer = setTimeout(() => {
                 this.status = 'rejected';
                 this.value = reason;
                 this.rejectedAry.forEach(item => item(this.value))
             }, 0);
         }
         try {
             excutorCallBack(resolveFn, rejectFn);
         } catch (err) {
             rejectFn(err)
         }
     }
     then(fulfilledCallBack, rejectedCallBack) {
          this.fulfillAry.push(fulfilledCallBack)
          this.rejectedAry.push(rejectedCallBack)

     }
 }
  export {
     Promise
 }

这样一个简单的promise就实现了,我们可以测试一下:如果小于1,打印100,如果大于1,打印-100


        import {Promise} from  './promise.js';

        new Promise((resolve, reject) => {
            setTimeout(() => {
                Math.random()*2 < 1 ? resolve(100) : reject(-100)
            }, 1000)
        }).then(res => {
            console.log(res)
        }, err => {
            console.log(err)
        })

完善链式调用.then().then().catch()

链式调用主要方法在.then()中,在调用之后应该返回一个promise对象,这样才可以继续调用.then()方法。

 class Promise {
     constructor(excutorCallBack) {
         this.status = 'pending';
         this.value = undefined;
         this.fulfillAry = [];
         this.rejectedAry = [];
         let resolveFn = result => {
             if (this.status !== 'pending') return;
             let timer = setTimeout(() => {
                 this.status = 'fulfilled';
                 this.value = result;
                 this.fulfillAry.forEach(item => {
                     item(this.value)
                 })
             }, 0);
         }
         let rejectFn = reason => {
             if (this.status !== 'pending') return;
             let timer = setTimeout(() => {
                 this.status = 'rejected';
                 this.value = reason;
                 this.rejectedAry.forEach(item => item(this.value))
             }, 0);
         }
         try {
             excutorCallBack(resolveFn, rejectFn);
         } catch (err) {
             rejectFn(err)
         }
     }
     then(fulfilledCallBack, rejectedCallBack) {
         typeof fulfilledCallBack != 'function' ? fulfilledCallBack = result => result : null;
         typeof rejectedCallBack != 'function' ? rejectedCallBack = reason => {
             throw new Error(reason instanceof Error ? reason.message : reason);
         } : null
         return new Promise((resolve, reject) => {
             this.fulfillAry.push(() => {
                 try {
                     let x = fulfilledCallBack(this.value);
                     x instanceof Promise ? x.then(resolve, reject) : resolve(x);
                 } catch (err) {
                     reject(err)
                 }
             })
             this.rejectedAry.push(() => {
                 try {
                     let x = this.rejectedCallBack(this.value);
                     x instanceof Promise ? x.then(resolve, reject) : resolve(x);
                 } catch (err) {
                     reject(err)
                 }
             })
         })
         //  this.fulfillAry.push(fulfilledCallBack)
         //  this.rejectedAry.push(rejectedCallBack)

     }
     catch (rejectedCallBack) {
         return this.then(null, rejectedCallBack)
     }
 }
 export {
     Promise
 }

我们再测试一下


        import {Promise} from  './promise.js';
      
        let p1 = new Promise((resolve, reject) => {
            setTimeout(() => {
                Math.random() < 0.5 ? resolve(100) : reject(-100)
            }, 1000)
        })
        let p2=p1.then(res => {
            return res+100;
        }, err => {
            console.log(err)
        })
        let p3=p2.then(res=>{
            console.log(res)
        },reason=>{
            console.log(reason)
        })

一个可以链式调用的promise就完成了。

如果哪块有问题欢迎大佬指点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值