promise 完成(es6 完全源码)

概览

const PENDING = Symbol('PENDING');
const FULFILLED = Symbol('FULFILLED');
const REJECTED = Symbol('REJECTED');

class MyPromise {
    constructor(fn) {}
    then(successFn, failFn) {}
    catch(failFn) {}
    finally(finalFn){}
    static resolve(val) {}
    static reject(val) {}
    static all(promiseArr) {}
    static race(promiseArr) {}
}

Promise 内部维护着三种状况 pendingfulfilledrejected,状况只能从 pending 改变到 fulfilled,或从 pending 改变到 rejected 且该改变不可逆。

Promise 重要供应了三个实例要领 then,catch,finally,和4个静态要领 resolve,reject,all,race。一切要领都都返回一个Promise对象。

组织函数

    constructor(fn) {
        this.fulfilledQueue = [];
        this.rejectedQueue = [];
        this._status = PENDING;
        this._value  = null;

        // 实行胜利行列中的回调函数
        const handleFulfilledQueue = () => {
            while(this.fulfilledQueue.length) {
                let fulfiledFn = this.fulfilledQueue.shift();
                fulfiledFn(this._value);
            };
        };
        
        // 实行失利行列中的回调函数
        const handleRejectedQueue = () => {
            while(this.rejectedQueue.length) {
                let rejectedFn = this.rejectedQueue.shift();
                rejectedFn(this._value);
            };
        };

        // 完成状况改变,实行回调行列中的回调函数
        const _resolve = (val) => {
            const fn = () => {
                if(this._status !== PENDING) {
                    return;
                }
                if(val instanceof MyPromise) {
                    val.then((res) => {
                        this._status = FULFILLED;
                        this._value = res;
                        handleFulfilledQueue();
                    }, (err) => {
                        this._status = REJECTED;
                        this._value = err;
                        handleRejectedQueue();
                    });
                } else {
                    this._status = FULFILLED;
                    this._value = val;
                    handleFulfilledQueue();
                }
            }
            // 保证promise 回调函数一定是在同步使命以后实行;
            setTimeout(fn, 0);
        }
        // 完成状况Pending到REJECTED的改变,实行rejected行列中的回调函数
        const _reject = (val) => {
            const fn = () => {
                if(this._status !== PENDING) {
                    return;
                }
                this._status = REJECTED;
                this._value = val;
                handleRejectedQueue();
            }
            setTimeout(fn, 0);
        }
        
        try {  // 处置惩罚外部传入函数实行非常
            fn(_resolve, _reject);            
        } catch(e) {
            return _reject(e);
        }
    }

Promise 组织函数吸收一个函数实行器作为参数,该实行器的两个参数 _resolve、_reject均为函数范例,由 Promise 内部完成。实行器在 Promise 组织函数中被马上实行。

注重: MyPromise 运用 Timeout 完成异步,使得 MyPromise 只能增加 macrotask,实际上原生的Promise 是 microtask

then 要领

    then(successFn, failFn) {
        return new MyPromise((resolve, reject) => {
            // 实行胜利时的回调函数
            const handleSucess = (fn) => {
                try {
                    if(typeof fn === 'function') {
                        const res = fn(this._value);
                        if(res instanceof MyPromise) {
                            res.then(resolve, reject);
                        } else {
                            resolve(res);
                        }
                    } else {
                        resolve(this._value)
                    }
                } catch(e){
                    reject(e);
                }
            }
            // 实行失利时的回调函数
            const handleFail = (fn) => {
                try {
                    if(typeof fn === 'function') {
                        const res = fn(this._value);
                        if(res instanceof MyPromise) {
                            res.then(resolve, reject);
                        } else {
                            resolve(res);
                        }
                    } else {
                        reject(this._value);
                    }
                } catch(e) {
                    reject(e);
                }
            }
            switch(this._status){
                case PENDING:       // 异步使命还没有完成,将回调函数推入响应行列
                    this.fulfilledQueue.push(() => {
                        handleSucess(successFn);
                    });
                    this.rejectedQueue.push(() => {
                        handleFail(failFn);
                    });
                    break;
                case FULFILLED:     // 异步使命胜利完成,实行胜利回调函数
                    handleSucess(successFn);
                    break;
                case REJECTED:      // 异步使命已失利,实行失利回调函数
                    handleFail(failFn);
                    break;
                default:
                    console.log('Promise error status:', this._status);
                    break;
            };
        });
    }

then 要领是 Promise 的一个重要要领,catch 和 finally 都可以用 then 来完成。当 Promise 的状况已流转时,回调函数会马上被实行,当 Promise 还处于 Pending 状况时,回调函数被推入响应行列中守候实行。

完全代码

class MyPromise {
    constructor(fn) {
        this.fulfilledQueue = [];
        this.rejectedQueue = [];
        this._status = PENDING;
        this._value  = null;

        const handleFulfilledQueue = () => {
            while(this.fulfilledQueue.length) {
                let fulfiledFn = this.fulfilledQueue.shift();
                fulfiledFn(this._value);
            };
        };
        const handleRejectedQueue = () => {
            console.log(this.rejectedQueue);
            while(this.rejectedQueue.length) {
                let rejectedFn = this.rejectedQueue.shift();
                rejectedFn(this._value);
            };
        };

        // 完成状况改变,实行回调行列中的回调函数
        const _resolve = (val) => {
            const fn = () => {
                if(this._status !== PENDING) {
                    return;
                }
                if(val instanceof MyPromise) {
                    val.then((res) => {
                        this._status = FULFILLED;
                        this._value = res;
                        handleFulfilledQueue();
                    }, (err) => {
                        this._status = REJECTED;
                        this._value = err;
                        handleRejectedQueue();
                    });
                } else {
                    this._status = FULFILLED;
                    this._value = val;
                    handleFulfilledQueue();
                }
            }
            setTimeout(fn, 0);
        }
        // 完成状况Pending到REJECTED的改变,实行rejected行列中的回调函数
        const _reject = (val) => {
            const fn = () => {
                if(this._status !== PENDING) {
                    return;
                }
                this._status = REJECTED;
                this._value = val;
                handleRejectedQueue();
            }
            setTimeout(fn, 0);
        }
        
        try { // 处置惩罚外部传入函数实行非常
            fn(_resolve, _reject);            
        } catch(e) {
            
            return _reject(e);
        }
    }

    then(successFn, failFn) {
        return new MyPromise((resolve, reject) => {
            // 实行胜利时的回调函数
            const handleSucess = (fn) => {
                try {
                    if(typeof fn === 'function') {
                        const res = fn(this._value);
                        if(res instanceof MyPromise) {
                            res.then(resolve, reject);
                        } else {
                            resolve(res);
                        }
                    } else {
                        resolve(this._value)
                    }
                } catch(e){
                    reject(e);
                }
            }
            // 实行失利时的回调函数
            const handleFail = (fn) => {
                try {
                    if(typeof fn === 'function') {
                        const res = fn(this._value);
                        if(res instanceof MyPromise) {
                            res.then(resolve, reject);
                        } else {
                            resolve(res);
                        }
                    } else {
                        reject(this._value);
                    }
                } catch(e) {
                    reject(e);
                }
            }
            switch(this._status){
                case PENDING:       // 异步使命还没有完成,将回调函数推入响应行列
                    this.fulfilledQueue.push(() => {
                        handleSucess(successFn);
                    });
                    this.rejectedQueue.push(() => {
                        handleFail(failFn);
                    });
                    break;
                case FULFILLED:     // 异步使命胜利完成,实行胜利回调函数
                    handleSucess(successFn);
                    break;
                case REJECTED:      // 异步使命已失利,实行失利回调函数
                    handleFail(failFn);
                    break;
                default:
                    console.log('Promise error status:', this._status);
                    break;
            };
        });
    }

    catch(failFn) {
        return this.then(null, failFn);
    }

    finally(finalFn){
        return this.then(finalFn, finalFn);
    }

    static resolve(val) {
        if(val instanceof MyPromise) {
            return val;
        } else {
            return new MyPromise((resolve, reject) =>{
                resolve(val);
            });
        }
    }

    static reject(val) {
        return new MyPromise((resolve, reject) => {     
            reject(val);
        });
    }

    static all(promiseArr) {
        return new Promise((resolve, reject) =>{
            const len = promiseArr.length;
            let count = 0;
            let result = [];
            for(let i = 0; i < len; i++) {
                promiseArr[i].then((val) => {
                    count++;
                    result.push[val];
                    if(count === len){
                        resolve(result);
                    }
                }, (err) => {
                    reject(err);
                });
            }
        });
    }

    static race(promiseArr) {
        return new Promise((resolve, reject) =>{
            const len = promiseArr.length;
            for(let i = 0; i < len; i++) {
                promiseArr[i].then((val) => {
                    resolve(val);
                }, (err) => {
                    reject(err);
                });
            }
        });
    }
}
    原文作者:coco
    原文地址: https://segmentfault.com/a/1190000018769632
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞