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就完成了。

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

你可能感兴趣的:(es6 promise实现)