Promise A+规范和 Promise实现

promise A+ 规范

  1. Promise 有三种状态:pending(进行中)、fulfilled(成功)、rejected(失败)。有一个执行器executor(new Promise 时传入的函数),且立即执行
  2. 状态转换:
    默认状态为pending
    状态只能 pending => fulfilled
    pending=> rejected
    两个转换状态方法
    成功:resolve(),状态pending => fulfilled,内部维护成功值 value undefined | thenable | promise
    失败:reject()状态pending=> rejected,内部维护失败原因 reason
  3. then方法:接收两个回调函数onFulfilled,onRejected
    成功时:执行onFulfilled,参数成功值value
    失败时:执行onRejected,参数为失败原因reason
    有异常:执行onRejeted
  4. Promise 可以连式调用,即then 返回的为新的promise
  5. 一个Promise可以重复调用
  6. then 返回值可穿透
  7. then 为异步执行

Promise 简单实现

// Promise 有三种状态
const PENDING = 'PENDING';
const FULFILLED = 'FULFILLED';
const REJECTED = 'REJECTED';

class Promise {
   constructor(executor) {
        //默认状态为pending
        //  状态只能    pending => fulfilled
        //             pending=> rejected
       this.status = PENDING;
       //维护内部成功失败的值
       this.value = undefined;
       this.reason = undefined;

       // 存放回调
       this.onResolvedCallbacks = [];
       // 存放失败的回调
       this.onRejectedCallbacks = [];

       // 成功回调
       let resolve = value => {
           // 单向流转
           if(this.status === PENDING) {
               this.status = FULFILLED;
               this.value = value;
               this.onResolvedCallbacks.forEach(fn => fn());
           }
       }

       // 失败的回调
       let reject = reason => {
           // 单向流转
           if(this.status === PENDING) {
               this.status = REJECTED;
               this.reason = reason;
               this.onRejectedCallbacks.forEach(fn => fn());
           }
       }

       // 立即执行
       try {
           executor(resolve, reject);
       } catch(error) {
           reject(error);
       }
   }

   if (this.status === FULFILLED) {
       onFulfilled(this.value);
   }

   if (this.status === REJECTED) {
       onRejected(this.reason);
   }
   if (this.status === PENDING) {
       // 存放执行队列
       this.onResolvedCallbacks.push(() => {
           onFulfilled(this.value);
       })
       this.onRejectedCallbacks.push(() => {
           onRejected(this.reason);
       })
   }
}
// 优化
class myPromise {
    constructor(executor) {
        this.status = 'PENDING';
        this.value = undefined;
        this.reason = undefined;
 
        this.onResolvedCallbacks = [];
        this.onRejectedCallbacks = [];
 
        let resolve = value => {
            if (this.status === 'PENDING') {
                this.status = 'FULFILLED';
                this.value = value;
                this.onResolvedCallbacks.forEach(fn => fn());
            }
        }
 
        let reject = reason => {
            if (this.status === 'PENDING') {
                this.status = 'REJECTED';
                this.reason = reason;
                this.onRejectedCallbacks.forEach(fn => fn());
            }
        }
 
        try {
            executor(resolve, reject);
        } catch (error) {
            reject(error);
        }
    }
 
    then(onFulfilled, onRejected) {
        // 边缘检测,为了继续连式调用
        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
        onRejected = typeof onRejected === 'function' ? onRejected : error => { throw error };
        // 连式调用,返回promise2
        let promise2 = new myPromise((resolve, reject) => {
            if (this.status === 'FULFILLED') {
                setTimeout(() => {
                    try {
                        let x = onFulfilled(this.value);
                        this.resolvePromise(promise2, x, resolve, reject);
                    } catch (error) {
                        reject(error);
                    }
                }, 0);
            }
 
            if (this.status === 'REJECTED') {
                setTimeout(() => {
                    try {
                        let x = onRejected(this.reason);
                        this.resolvePromise(promise2, x, resolve, reject);
                    } catch (error) {
                        reject(error);
                    }
                }, 0);
            }
 
            if (this.status === 'PENDING') {
                this.onResolvedCallbacks.push(() => {
                    setTimeout(() => {
                        try {
                            let x = onFulfilled(this.value);
                            this.resolvePromise(promise2, x, resolve, reject);
                        } catch (error) {
                            reject(error);
                        }
                    }, 0);
                });
 
                this.onRejectedCallbacks.push(() => {
                    setTimeout(() => {
                        try {
                            let x = onRejected(this.reason);
                            this.resolvePromise(promise2, x, resolve, reject);
                        } catch (error) {
                            reject(error);
                        }
                    }, 0);
                });
            }
        });
 
        return promise2;
    } catch(onRejected) {
        return this.then(null, onRejected);
    }
 
    resolvePromise(promise2, x, resolve, reject) {
        if (promise2 === x) {
            return reject(new TypeError('Promise 不能循环连式调用自身'));
        }
 
        let called = false;
        if (x instanceof Promise) {
            // 如果是xPromise,调用自身地柜
            x.then(y => {
                this.resolvePromise(promise2, y, resolve, reject);
            }, error => {
                reject(error);
            });
        } else if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
            // 如果 x 是对象或函数,then = x.then
            try {
                let then = x.then;
                if (typeof then === 'function') {
                    //如果then是函数就说明 x 是一个 promise 对象.
                    //那就调用 then,并且把 x 作为 this,
                    //然后在成功回调中继续调用 resolvePromise 并且把拿到的值作为新的 x 传入,其他不变
                    then.call(x, y => {
                        if (called) return;
                        called = true;
                        this.resolvePromise(promise2, y, resolve, reject);
                    }, error => {
                        if (called) return;
                        called = true;
                        reject(error);
                    });
                } else {
                    // then 不是一个函数,则x是一个对象
                    resolve(x);
                }
            } catch (error) {            
                if (called) return;
                called = true;
                reject(error);
            }
        } else {
            // 都不是
            resolve(x);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值