Promise源码实现

34次阅读

共计 3255 个字符,预计需要花费 9 分钟才能阅读完成。

const ENUM = {
    PENDING: 'PENDING',
    FULFILLED: 'FULFILLED',
    REJECTED: 'REJECTED'
}
// 需要兼容其他人的 promise
const resolvePromise = (x, promise2, resolve, reject) => {if (x === promise2) {reject(new TypeError(`TypeError: Chaining cycle detected for promise #<Promise>`))
    }
    if ((typeof x === 'object' && x !== null) || typeof x === 'function') {
        let called;
        try {
            let then = x.then; 
            if (typeof then == 'function') {
                then.call(x, y => {if (called) return;
                    called = true;
                    resolvePromise(y, promise2, resolve, reject);
                }, r => {if (called) return;
                    called = true;
                    reject(r);
                })
            } else {resolve(x); // {a:1}
            }
        } catch (e) {if (called) return;
            called = true;
            reject(e);
        }
    } else {resolve(x); 
    }
}
class Promise {constructor(executor) {
        this.status = ENUM.PENDING;
        this.value = undefined; // 实例上的属性 每次 new 都会创建一个新的
        this.reason = undefined;
        // 需要创建成功的队列 失败的队列,分别存放
        this.onResolvedCallbacks = [];
        this.onRejectedCallbacks = [];
        const resolve = (value) => {
            // 如果 value 是一个 promise,那我们的库中应该也要实现一个递归解析
            if(value instanceof Promise){
                // 递归解析 
                return value.then(resolve,reject)
            }
            if (this.status === ENUM.PENDING) {
                this.status = ENUM.FULFILLED;
                this.value = value; // 先赋予的值 再循环
                this.onResolvedCallbacks.forEach(fn => fn())
            }
        }
        const reject = (reason) => {if (this.status === ENUM.PENDING) {
                this.status = ENUM.REJECTED;
                this.reason = reason;
                this.onRejectedCallbacks.forEach(fn => fn())
            }
        }
        try {executor(resolve, reject);
        } catch (e) {reject(e)
        }
    }
    then(onFulfilled, onRejected) {
        onFulfilled = typeof onFulfilled == 'function' ? onFulfilled : v => v;
        onRejected = typeof onRejected === 'function' ? onRejected : err => {throw err};
        // 调用 then 方法 创建一个新的 promise
        let promise2 = new Promise((resolve, reject) => {
            // 我需要根据 x 的状况来判断是调用 resolve 还是 reject
            if (this.status == ENUM.FULFILLED) {
                // todo...
                setTimeout(() => {
                    try {let x = onFulfilled(this.value);
                        // 解析 promise
                        resolvePromise(x, promise2, resolve, reject)
                    } catch (e) {reject(e);
                    }
                }, 0);
            }
            if (this.status == ENUM.REJECTED) {
                // todo...
                setTimeout(() => {
                    try {let x = onRejected(this.reason);
                        resolvePromise(x, promise2, resolve, reject)
                    } catch (e) {reject(e);
                    }
                }, 0);
            }
            if (this.status == ENUM.PENDING) {
                // 用户还没有调用 resolve 或者 reject 方法
                this.onResolvedCallbacks.push(() => {
                    // todo...
                    setTimeout(() => {
                        try {let x = onFulfilled(this.value);
                            resolvePromise(x, promise2, resolve, reject)
                        } catch (e) {reject(e);
                        }
                    }, 0);
                });
                this.onRejectedCallbacks.push(() => {
                    // todo...
                    setTimeout(() => {
                        try {let x = onRejected(this.reason);
                            resolvePromise(x, promise2, resolve, reject)
                        } catch (e) {reject(e);
                        }
                    }, 0);

                })
            }
        });
        return promise2;
    }
    catch(errCallback){return this.then(null,errCallback)
    }
    static resolve(val){return new Promise((resolve,reject)=>{resolve(val);
        })
    }
    static reject(reason){return new Promise((resolve,reject)=>{reject(reason);
        })
    }
}
// 产生延迟对象

Promise.prototype.finally = function(callback) {return this.then((value) => {return Promise.resolve(callback()).then(() => value)
    }, (err) => {return Promise.resolve(callback()).then(() => { throw err})
    });
}
Promise.all = function(values) {return new Promise((resolve, reject) => {let resultArr = [];
        let orderIndex = 0;
        const processResultByKey = (value, index) => {resultArr[index] = value;
            if (++orderIndex === values.length) {resolve(resultArr)
            }
        }
        for (let i = 0; i < values.length; i++) {let value = values[i];
            if (value && typeof value.then === 'function') {value.then((value) => {processResultByKey(value, i);
                }, reject);
            } else {processResultByKey(value, i);
            }
        }
    });
}
Promise.race = function(promises) {return new Promise((resolve, reject) => {
        // 一起执行就是 for 循环
        for (let i = 0; i < promises.length; i++) {let val = promises[i];
            if (val && typeof val.then === 'function') {val.then(resolve, reject); // value.then(resolve,reject)
            } else { // 普通值
                resolve(val)
            }
        }
    });
}

正文完
 0