手写Promise--并且分析Promise过程

分为三个模块:

1: Promise函数
2: Promise.prototype.then
3:  resolvePromise

一:Promise函数

1:定义三种状态
2:定义Promise函数,定义接收参数为executor 执行器
3:定义this指向
4: 定义初始化状态
5:定义成功/失败时候的回调
6:定义resolve函数, 定义接收参数为value
6.1:判断初始状态 , 条件为真改变状态,同时定义值
6.2:对成功时候的回调进行遍历循环执行
7:定义reject函数, 定义接收参数为 reason
7.1:同6.1
7.2:同6.2 , 对失败时候的回调进行遍历
8:尝试执行执行器,执行器接收二个参数(resolve ,reject), catch(e) reject(e)

二: Promise.prototype.then

1: 函数接收成功回调/失败回调作为参数
2:判断回调是否为函数
3:定义一个Promise2  = 实例化Promise,实例化时,Promise有三种状态
4:判断是否为第一种状态Fulfilled
4.1:在延迟器setTimeout 执行try-catch
4.2: try- 执行成功回调,并将value值传入,得到x
4.3:执行resolvePromise函数,并且将promise2 , x ,resolve ,reject 作为参数传入
4.4:catch- reject(e)
5:判断状态是否为rejected
5.1:等同于4.1
5.2:等同于4.2- 执行失败回调,并将reason值传入
5.3:等同于4.3
5.4:等同于4.4
6:判断状态是否为PENDING时, 有两种状态
6.1:为onFulfilled,执行self.onFulfilled.push()
6.2: 4.1---- 4.4  执行的是成功的回调
6.3:为onRejected , 执行self.onRejected.push()
6.4: 4.1----4.4  执行的是失败的回调

三: resolvePromise 函数

1: 定义resolvePromise函数, 接收四个参数promise2 , x , resolve , reject 
2:判断promise2 是否等于 x  ,条件真抛出错误 rejected(new TypeErr)
3: 判断 x 是否为真 or x=object   or x=function
4: 条件真 执行5  条件假: 直接resolve(x)
5: 定义一个lock :userd , 进行尝试执行try ,catch(e)
6: 此时x 为一个obj or fn , 得到 then , x.then
7: 对then 进行判断是否为函数, 是函数执行8 , 不是函数 直接resovle(x)
8:条件真执行 then.call(x, ((y)=>{}) ,((z)=>{})
9: x为this , y :开锁,并且将resolvePromise()函数进行再次执行, z:开锁, 直接reject(z)

Promise 实现代码

/*
 *1 new Promise 时 , 需要传递一个excutor 执行器 , 执行器立刻执行
 *2 excutor 接受二个参数 , 分别是resolve 和 reject 
 *3 Promise 只能从pending 到 rejected 或者从 pending 到 fulfilled
 *4 Promise 到状态一旦确认 , 就不会再改变
 *5 Promise 都有then 方法, then方法接受俩个参数, 分别是Promise 成功的回调onfufilled , 和Promise 失败的回调 onReject
 *6 如果调用then 时, Promise 已经成功 。 则执行onfulfilled , 并将promise的值作为参数传递出去
 *  如果已经失败 , 那么执行 onRejected  并将Promise 失败的原因作为参数传递进去
 *  如果状态是pending 需要将 onfulfilled 和onRejected 函数存放起来,等待状态确定后,再依次将对应的函数执行(发布订阅)
 *
 * then 的参数onFulfilled 和 onRejected 可以缺省
 * Promise 可以then 多次, Promise 方法返回一个Promise
 * 
 */


//  定义状态
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
function Promise(executor) {
    let self = this;
    self.status = PENDING;
    self.onFulfilled = [];//成功的回调
    self.onRejected = []; //失败的回调
    //PromiseA+ 2.1
    function resolve(value) {
        if (self.status === PENDING) {
            self.status = FULFILLED;
            self.value = value;
            self.onFulfilled.forEach(fn => fn());//PromiseA+ 2.2.6.1
        }
    }

    function reject(reason) {
        if (self.status === PENDING) {
            self.status = REJECTED;
            self.reason = reason;
            self.onRejected.forEach(fn => fn());//PromiseA+ 2.2.6.2
        }
    }

    try {
        executor(rzesolve, reject);
    } catch (e) {
        reject(e);
    }
}

Promise.prototype.then = function (onFulfilled, onRejected) {
    //PromiseA+ 2.2.1 / PromiseA+ 2.2.5 / PromiseA+ 2.2.7.3 / PromiseA+ 2.2.7.4
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
    onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason };
    let self = this;
    //PromiseA+ 2.2.7
    let promise2 = new Promise((resolve, reject) => {
        if (self.status === FULFILLED) {
            //PromiseA+ 2.2.2
            //PromiseA+ 2.2.4 --- setTimeout
            setTimeout(() => {
                try {
                    //PromiseA+ 2.2.7.1
                    let x = onFulfilled(self.value);
                    resolvePromise(promise2, x, resolve, reject);
                } catch (e) {
                    //PromiseA+ 2.2.7.2
                    reject(e);
                }
            });
        } else if (self.status === REJECTED) {
            //PromiseA+ 2.2.3
            setTimeout(() => {
                try {
                    let x = onRejected(self.reason);
                    resolvePromise(promise2, x, resolve, reject);
                } catch (e) {
                    reject(e);
                }
            });
        } else if (self.status === PENDING) {
            self.onFulfilled.push(() => {
                setTimeout(() => {
                    try {
                        let x = onFulfilled(self.value);
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        reject(e);
                    }
                });
            });
            self.onRejected.push(() => {
                setTimeout(() => {
                    try {
                        let x = onRejected(self.reason);
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        reject(e);
                    }
                });
            });
        }
    });
    return promise2;
}

function resolvePromise(promise2, x, resolve, reject) {
    //PromiseA+ 2.3.1
    if (promise2 === x) {
        reject(new TypeError('Chaining cycle'));
    }
    if (x && typeof x === 'object' || typeof x === 'function') {
        let used; //PromiseA+2.3.3.3.3 只能调用一次
        try {
            let then = x.then;
            if (typeof then === 'function') {
                //PromiseA+2.3.3
                then.call(x, (y) => {
                    //PromiseA+2.3.3.1
                    if (used) return;
                    used = true;
                    resolvePromise(promise2, y, resolve, reject);
                }, (r) => {
                    //PromiseA+2.3.3.2
                    if (used) return;
                    used = true;
                    reject(r);
                });

            }else{
                //PromiseA+2.3.3.4
                if (used) return;
                used = true;
                resolve(x);
            }
        } catch (e) {
            //PromiseA+ 2.3.3.2
            if (used) return;
            used = true;
            reject(e);
        }
    } else {
        //PromiseA+ 2.3.3.4
        resolve(x);
    }
}

 

//测试用---------------------
Promise.defer = Promise.deferred = function () {
    let dfd = {};
    dfd.promise = new Promise((resolve, reject) => {
        dfd.resolve = resolve;
        dfd.reject = reject;
    });
    return dfd;
}









module.exports = Promise
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值