手撸Promise

基础版promise
// 三个状态: PENDING、FULFILLED、REJECTED
const PENDING = 'PENDING';
const FULFILLED = 'FULFILLED';
const REJECTED = 'REJECTED';

class Promise {
    constructor(executor) {
        // 默认状态为 PENDING
        this.status = PENDING;
        // 存放成功状态的值,默认为undefined
        this.value = undefined;
        // 存放失败状态的值,默认为undefined
        this.reason = undefined;

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

        // 调用此方法即成功
        let resolve = ( value ) => {
            // 状态为PENDING时才可以更新状态,防止executor中调用了两次 resovle/reject 方法
            if (this.status === PENDING) {
                this.status = FULFILLED;
                this.value = value;
                // 依次将对应的函数执行
                this.onResolvedCallbacks.forEach(fn => fn());
            }
        }

        // 调用此方法就是失败
        let reject = ( reason ) => {
            // 状态为PENDING时才可以更新状态,防止executor中调用了两次 resovle/reject 方法
            if (this.status === PENDING) {
                this.status = REJECTED;
                this.reason = reason;
                // 依次将对应的函数执行
                this.onRejectedCallbacks.forEach(fn => fn());
            }
        }

        try {
            // 立即执行,将resolve和reject函数传给使用者
            executor(resolve, reject)
        } catch (error) {
            // 发生异常时执行失败逻辑
            reject(error)
        }
    }

    // 包含一个then方法,并接收两个参数 onFulfilled、onRejected
    then(onFulfilled, onRejected) {
        if (this.status === FULFILLED) {
            onFulfilled(this.value)
        }

        if (this.status === REJECTED) {
            onRejected(this.reason)
        }
        
        if (this.status === PENDING) {
            // 如果promise的状态是 pending,需要将 onFulfilled 和 onRejected 函数存放起来,等待状态确定后,再依次将对应的函数执行
            this.onResolvedCallbacks.push(() => {
                onFulfilled(this.value)
            })

            // 如果promise的状态是 pending,需要将 onFulfilled 和 onRejected 函数存放起来,等待状态确定后,再依次将对应的函数执行
            this.onRejectedCallbacks.push(() => {
                onRejected(this.reason)
            })
        }
    }
}

// 同步操作的Promise
// const promise = new Promise((resolve, reject) => {
//     resolve('成功')
// }).then( data => {
//     console.log('success', data)
// }, err => {
//     console.log('failed', err)
// })

// 异步操作Promise
const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        reject('失败')
    }, 1000);
}).then( data => {
    console.log('success', data)
}, err => {
    console.log('failed', err)
})
then的链式调用和值穿透性

then的链式调用:使用 Promise 的时候,当 then 函数中 return 了一个值,不管是什么值,我们都能在下一个 then 中获取到。

值穿透性:当我们不在then中放入参数,例promise.then().then(),那么其后面的then依旧可以得到之前then返回的值。

完整版promise
// 1、then 的参数 onFulfilled 和 onRejected 可以缺省,如果 onFulfilled 或者 onRejected不是函数,将其忽略,且依旧可以在下面的 then 中获取到之前返回的值;「规范 Promise/A+ 2.2.1、2.2.1.1、2.2.1.2」
// 2、promise 可以 then 多次,每次执行完 promise.then 方法后返回的都是一个“新的promise";「规范 Promise/A+ 2.2.7」
// 3、如果 then 的返回值 x 是一个普通值,那么就会把这个结果作为参数,传递给下一个 then 的成功的回调中;
// 4、如果 then 中抛出了异常,那么就会把这个异常作为参数,传递给下一个 then 的失败的回调中;「规范 Promise/A+ 2.2.7.2」
// 5、如果 then 的返回值 x 是一个 promise,那么会等这个 promise 执行完,promise 如果成功,就走下一个 then 的成功;如果失败,就走下一个 then 的失败;如果抛出异常,就走下一个 then 的失败;「规范 Promise/A+ 2.2.7.3、2.2.7.4」
// 6、如果 then 的返回值 x 和 promise 是同一个引用对象,造成循环引用,则抛出异常,把异常传递给下一个 then 的失败的回调中;「规范 Promise/A+ 2.3.1」
// 7、如果 then 的返回值 x 是一个 promise,且 x 同时调用 resolve 函数和 reject 函数,则第一次调用优先,其他所有调用被忽略;「规范 Promise/A+ 2.3.3.3.3」

// 三个状态: PENDING、FULFILLED、REJECTED
const PENDING = 'PENDING';
const FULFILLED = 'FULFILLED';
const REJECTED = 'REJECTED';

const resolvePromise= ( promise2, x, resolve, reject ) => {
    // 自己等待自己完成是错误的实现,用一个类型错误,结束掉 promise  ----> Promise/A+ 2.3.1
    if (promise2 === x) {
        return reject('失败123')
    }
    //------> Promise/A+ 2.3.3.3.3 只能调用一次
    let called;
    // 后续的条件要严格判断 保证代码能和别的库一起使用
    if((typeof x === 'object' && x !== null) || typeof x === 'function') {
        try {
            // 为了判断resolve过的就不用再reject了(比如 reject 和 resolve 同时调用的时候)-----> Promise/A+ 2.3.3.1
            let then = x.then;
            if (typeof then === 'function') {
                // 不要写成 x.then,直接 then.call 就可以了 因为 x.then 会再次取值,Object.defineProperty  Promise/A+ 2.3.3.3
                then.call(x, y => { // 根据promise状态决定是成功还是失败
                    if(called) return;
                    called = true;
                    // 递归解析(可能promise中还有promise) ----> Promise/A+ 2.3.3.3.1
                    resolvePromise(promise2, y, resolve, reject);
                }, r => {
                    // 只要失败就失败 ---->  Promise/A+ 2.3.3.3.2
                    if (called) return;
                    called = true;
                    reject(r)
                })
            } else {
                // 如果 x.then 是个普通值就直接返回 resolve 作为结果  Promise/A+ 2.3.3.4
                resolve(x);
            }
        } catch (e) {
            // Promise/A+ 2.3.3.2
            if (called) return;
            called = true;
            reject(e)
        }
    } else {
        // 如果 x 是个普通值就直接返回 resolve 作为结果  Promise/A+ 2.3.4  
        resolve(x)
    }
}

class FullPromise {
    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) {
        //解决 onFufilled,onRejected 没有传值的问题
        //Promise/A+ 2.2.1 / Promise/A+ 2.2.5 / Promise/A+ 2.2.7.3 / Promise/A+ 2.2.7.4
        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v;
        //因为错误的值要让后面访问到,所以这里也要跑出个错误,不然会在之后 then 的 resolve 中捕获
        onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err };
        // 每次调用 then 都返回一个新的 promise  Promise/A+ 2.2.7
        let promise2 = new Promise((resolve, reject) => {
            if (this.status === FULFILLED) {
                //Promise/A+ 2.2.2
                //Promise/A+ 2.2.4 --- setTimeout
                setTimeout(() => {
                    try {
                        //Promise/A+ 2.2.7.1
                        let x = onFulfilled(this.value);
                        // x可能是一个proimise
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        //Promise/A+ 2.2.7.2
                        reject(e)
                    }
                }, 0);
            }
            if (this.status === REJECTED) {
                //Promise/A+ 2.2.3
                setTimeout(() => {
                  try {
                    let x = onRejected(this.reason);
                    resolvePromise(promise2, x, resolve, reject);
                  } catch (e) {
                    reject(e)
                  }
                }, 0);
            }
            if (this.status === PENDING) {
                this.onResolvedCallbacks.push(() => {
                    setTimeout(() => {
                        try {
                            let x = onFulfilled(this.value);
                            resolvePromise(promise2, x, resolve, reject);
                        } catch (e) {
                            reject(e)
                        }
                    }, 0);
                });
                this.onRejectedCallbacks.push(()=> {
                    setTimeout(() => {
                      try {
                        let x = onRejected(this.reason);
                        resolvePromise(promise2, x, resolve, reject)
                      } catch (e) {
                        reject(e)
                      }
                    }, 0);
                });
            }
            return promise2;
        });
    }
}

const promise = new Promise((resolve, reject) => {
    resolve('success')
}).then().then().then(data => {
    console.log(data)
}, err => {
    console.log('err', err);
})
原文地址:https://www.cnblogs.com/zppsakura/p/13897435.html