promise実現(s 6の完全なソース)


概要
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の内部は3つの状態pending、fulfilledとrejectiedを維持しています.状態はpendingからfulfilledに転換するか、あるいはpendingからrejectに移行するか、その変化は可逆的ではありません.
Promiseは主に3つの例示的な方法then,catch,finally,および4つの静的方法resolive,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コンストラクタはパラメータとして関数アクチュエータを受信します.このアクチュエータの二つのパラメータ_レスリング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);
                });
            }
        });
    }
}