promiseA+规范及应用

181 阅读9分钟

术语

  1. promise 是一个有then方法的对象或者是函数,行为遵循本规范。
  2. thenable 是一个有then方法的对象或者是函数。
  3. value 是promise状态成功时的值,也就是resolve的参数, 包括各种数据类型, 也包括undefined/thenable或者是 promise。
  4. reason 是promise状态失败时的值, 也就是reject的参数, 表示拒绝的原因。
  5. exception 是一个使用throw抛出的异常值。

规范

Promise States

promise应该有三种状态(pending, fulflled, rejected).

  1. pending

    • 初始的状态, 可改变.
    • 一个promise在resolve或者reject前都处于这个状态。
    • 1.3 可以通过 resolve -> fulfilled 状态;
    • 1.4 可以通过 reject -> rejected 状态;
  2. fulfilled

    • 最终态, 不可变;
    • 一个promise被resolve后会变成这个状态;
    • 必须拥有一个value值;
  3. rejected

    • 最终态, 不可变;
    • 一个promise被reject后会变成这个状态;
    • 必须拥有一个reason;

pending -> resolve(value) -> fulfilled pending -> reject(reason) -> rejected

then

promise应该提供一个then方法, 用来访问最终的结果, 无论是value还是reason.

promise.then(onFulfilled, onRejected)

1. 参数要求

  • onFulfilled 必须是函数类型, 如果不是函数, 应该被忽略.
  • onRejected 必须是函数类型, 如果不是函数, 应该被忽略.

2. onFulfilled 特性

  • 在promise变成 fulfilled 时,应该调用 onFulfilled, 参数是value
  • 在promise变成 fulfilled 之前, 不应该被调用.
  • 只能被调用一次(所以在实现的时候需要一个变量来限制执行次数)

3. onRejected 特性

  • 在promise变成 rejected 时,应该调用 onRejected, 参数是reason
  • 在promise变成 rejected 之前, 不应该被调用.
  • 只能被调用一次(所以在实现的时候需要一个变量来限制执行次数)

4. onFulfilled 和 onRejected 应该是微任务 这里用queueMicrotask来实现微任务的调用.

5. then方法可以被调用多次

  • promise状态变成 fulfilled 后,所有的 onFulfilled 回调都需要按照then的顺序执行, 也就是按照注册顺序执行(所以在实现的时候需要一个数组来存放多个onFulfilled的回调)
  • promise状态变成 rejected 后,所有的 onRejected 回调都需要按照then的顺序执行, 也就是按照注册顺序执行(所以在实现的时候需要一个数组来存放多个onRejected的回调)

6.返回值then 应该返回一个promise

 promise2 = promise1.then(onFulfilled, onRejected);
  • onFulfilled 或 onRejected 执行的结果为x, 调用 resolvePromise。
  • 如果 onFulfilled 或者 onRejected 执行时抛出异常e, promise2需要被reject。
  • 如果 onFulfilled 不是一个函数, promise2 以promise1的value 触发fulfilled。
  • 如果 onRejected 不是一个函数, promise2 以promise1的reason 触发rejected。

7. resolvePromise

resolvePromise(promise2, x, resolve, reject)
  • 如果 promise2 和 x 相等,那么 reject TypeError
  • 如果 x 是一个 promsie 如果x是pending态,那么promise必须要在pending,直到 x 变成 fulfilled or rejected. 如果 x 被 fulfilled, fulfill promise with the same value. 如果 x 被 rejected, reject promise with the same reason.
  • 如果 x 是一个 object 或者 是一个 function let then = x.then. 如果 x.then 这步出错,那么 reject promise with e as the reason. 如果 then 是一个函数,then.call(x, resolvePromiseFn, rejectPromise) resolvePromiseFn 的 入参是 y, 执行 resolvePromise(promise2, y, resolve, reject); rejectPromise 的 入参是 r, reject promise with r. 如果 resolvePromise 和 rejectPromise 都调用了,那么第一个调用优先,后面的调用忽略。 如果调用then抛出异常e 如果 resolvePromise 或 rejectPromise 已经被调用,那么忽略 则,reject promise with e as the reason 如果 then 不是一个function. fulfill promise with x.

promiseA+实现

1.定义三种状态

const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

class newPromise {
    constructor() {
        this.status = PENDING;
        this.value = null;
        this.reason = null;
    }
}

2.实现resolve()和reject()方法

  • 只有当status为pending时才执行其代码;
  • 改变staus 为 fulfilled/rejected;
  • 设置value/reason的值;
reject(reason) {
        if(this.status === PENDING) {
            this.status = REJECTED;
            this.reason = reason;
        }
    }

    resolve(value) {
        if(this.status === PENDING) {
            this.status = FULFILLED;
            this.value = value;
        }
    }

3.处理promise的入参

  • 入参是个函数 接收reject和resolve两个参数;
  • 初始化的时候就执行这个函数 并且报错时要通过reject抛出异常;
 constructor(fn) {
        this.status = PENDING;
        this.value = null;
        this.reason = null;

        try {
            fn(this.resolve.bind(this), this.reject.bind(this))
        } catch(error) {
            this.reject(error)
        }
    }

4.实现then方法

  • then接收两个参数, onFulfilled 和 onRejected;
  • 检查并处理参数, 如果不是function, 就忽略. 即原样返回value或者reason;
  • 如果 onFulfilled 不是函数且 promise1 成功执行, promise2 必须成功执行并返回相同的值
  • 如果 onRejected 不是函数且 promise1 拒绝执行, promise2 必须拒绝执行并返回相同的据因。
  • tip: 如果promise1的onRejected执行成功了,promise2应该被resolve
  • then的返回值整体是一个promise;
  • onFulfilled和onRejected是微任务,使用queueMicrotask包裹;
  • 如果 onFulfilled 或者 onRejected 抛出一个异常 e ,则 promise2 必须拒绝执行,并返回拒因 e。
  • 如果 onFulfilled 或者 onRejected 返回一个值 x ,则运行resovlePromise(promise2, x, resolve, reject);
  • 根据status执行相应的回调,status为rejected/fulfilled时执行相应的回调函数,当status为pending时将回调函数收集到相应的数组。
    FULFILLED_CALLBACK_LIST = [];
    REJECTED_CALLBACK_LIST = [];
 then(onFulfilled, onRejected) {
        // 入参为onFulfilled和onRejected并检查参数,如果不是function 就忽略,原样返回value或者reason
        const realOnFulfilled = this.isFunction(onFulfilled) ? onFulfilled : (value) => {
            return value
        }
        const realOnRejected = this.isFunction(onRejected) ? onRejected : (reason) => {
            throw reason;
        };
        // then 返回一个promise;
        const promise2 = new MPromise((resolve, reject) => {
            const fulfilledMicrotask = () => {
                // onFulfilled和onRejected为微任务,使用queueMicrotask包裹
                queueMicrotask(() => {
                    try {
                        // 如果 onFulfilled 或者 onRejected 返回一个值 x ,则运行resovlePromise(promise2, x, resolve, reject);
                        const x = realOnFulfilled(this.value);
                        this.resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        // 抛出一个异常 e ,则 promise2 必须拒绝执行,并返回拒因 e。
                        reject(e)
                    }
                })
            };
            const rejectedMicrotask = () => {
                queueMicrotask(() => {
                    try {
                        const x = realOnRejected(this.reason);
                        this.resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        reject(e);
                    }
                })
            }
            // 根据status执行相应的回调,status为rejected/fulfilled时执行相应的回调函数,当status为pending时将回调函数收集到相应的数组。
            switch (this.status) {
                case FULFILLED: {
                    fulfilledMicrotask()
                    break;
                }
                case REJECTED: {
                    rejectedMicrotask()
                    break;
                }
                case PENDING: {
                    this.FULFILLED_CALLBACK_LIST.push(fulfilledMicrotask)
                    this.REJECTED_CALLBACK_LIST.push(rejectedMicrotask)
                }
            }
        })
        return promise2
    }

使用ES6的getter和setter监听status的变化,待status变为fulfilled/rejected时执行相应回调数组中的回调函数。

    _status = PENDING;
    get status() {
        return this._status;
    }

    set status(newStatus) {
        this._status = newStatus;
        switch (newStatus) {
            case REJECTED:
                this.REJECTED_CALLBACK_LIST.forEach(calback => {
                    calback(this.reason);
                })
                break;
            case FULFILLED: 
                 this.FULFILLED_CALLBACK_LIST.forEach(callback => {
                     callback(this.value);
                 });
            break;
        }
    }

5.实现resolvePromise(promise2, x, resolve, reject);

    resolvePromise(promise2, x, resolve, reject) {
        // 如果 newPromise 和 x 指向同一对象,以 TypeError 为据因拒绝执行 newPromise
        if (promise2 === x) {
            return reject(new TypeError('The promise and the return value are the same'));
        }

        if (x instanceof MPromise) {
            // 如果 x 为 Promise ,则使 newPromise 接受 x 的状态
            // 也就是继续执行x,如果执行的时候拿到一个y,还要继续解析y
            queueMicrotask(() => {
                x.then((y) => {
                    this.resolvePromise(promise2, y, resolve, reject);
                }, reject);
            })
        } else if (typeof x === 'object' || this.isFunction(x)) {
            // 如果 x 为对象或者函数
            if (x === null) {
                // null也会被判断为对象
                return resolve(x);
            }

            let then = null;

            try {
                // 把 x.then 赋值给 then 
                // 这种首先保存 x.then 的引用,然后测试此引用,再调用此引用的处理,避免了对 x.then 属性的多次访问。这种预防措施在面对一些特殊访问器时十分重要,因为有的访问器每次访问都会导致其值的改变。
                then = x.then;
            } catch (error) {
                // 如果取 x.then 的值时抛出错误 e ,则以 e 为据因拒绝 promise
                return reject(error);
            }

            // 如果 then 是函数
            if (this.isFunction(then)) {
                let called = false;
                // 将 x 作为函数的作用域 this 调用
                // 传递两个回调函数作为参数,第一个参数叫做 resolvePromise ,第二个参数叫做 rejectPromise
                try {
                    then.call(
                        x,
                        // 如果 resolvePromise 以值 y 为参数被调用,则运行 resolvePromise
                        (y) => {
                            // 需要有一个变量called来保证只调用一次.
                            if (called) return;
                            called = true;
                            this.resolvePromise(promise2, y, resolve, reject);
                        },
                        // 如果 rejectPromise 以据因 r 为参数被调用,则以据因 r 拒绝 promise
                        (r) => {
                            if (called) return;
                            called = true;
                            reject(r);
                        });
                } catch (error) {
                    // 如果调用 then 方法抛出了异常 e:
                    if (called) return;

                    // 否则以 e 为据因拒绝 promise
                    reject(error);
                }
            } else {
                // 如果 then 不是函数,以 x 为参数执行 promise
                resolve(x);
            }
        } else {
            // 如果 x 不为对象或者函数,以 x 为参数执行 promise
            resolve(x);
        }
    }

6.完整代码

const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

class MPromise {
    FULFILLED_CALLBACK_LIST = [];
    REJECTED_CALLBACK_LIST = [];
    _status = PENDING;

    constructor(fn) {
        this.status = PENDING;
        this.value = null;
        this.reason = null;

        try {
            fn(this.resolve.bind(this), this.reject.bind(this))
        } catch(error) {
            this.reject(error)
        }
    }

    get status() {
        return this._status;
    }

    set status(newStatus) {
        this._status = newStatus;
        switch (newStatus) {
            case REJECTED:
                this.REJECTED_CALLBACK_LIST.forEach(calback => {
                    calback(this.reason);
                })
                break;
            case FULFILLED: 
                 this.FULFILLED_CALLBACK_LIST.forEach(callback => {
                     callback(this.value);
                 });
            break;
        }
    }

    reject(reason) {
        if(this.status === PENDING) {
            this.status = REJECTED;
            this.reason = reason;
        }
    }

    resolve(value) {
        if(this.status === PENDING) {
            this.status = FULFILLED;
            this.value = value;
        }
    }

    isFunction(value) {
        return typeof value === 'function'? true : false;
    }

    then(onFulfilled, onRejected) {
        // 入参为onFulfilled和onRejected并检查参数,如果不是function 就忽略,原样返回value或者reason
        const realOnFulfilled = this.isFunction(onFulfilled) ? onFulfilled : (value) => {
            return value
        }
        const realOnRejected = this.isFunction(onRejected) ? onRejected : (reason) => {
            throw reason;
        };
        // then 返回一个promise;
        const promise2 = new MPromise((resolve, reject) => {
            const fulfilledMicrotask = () => {
                // onFulfilled和onRejected为微任务,使用queueMicrotask包裹
                queueMicrotask(() => {
                    try {
                        // 如果 onFulfilled 或者 onRejected 返回一个值 x ,则运行resovlePromise(promise2, x, resolve, reject);
                        const x = realOnFulfilled(this.value);
                        this.resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        // 抛出一个异常 e ,则 promise2 必须拒绝执行,并返回拒因 e。
                        reject(e)
                    }
                })
            };
            const rejectedMicrotask = () => {
                queueMicrotask(() => {
                    try {
                        const x = realOnRejected(this.reason);
                        this.resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        reject(e);
                    }
                })
            }
            // 根据status执行相应的回调,status为rejected/fulfilled时执行相应的回调函数,当status为pending时将回调函数收集到相应的数组。
            switch (this.status) {
                case FULFILLED: {
                    fulfilledMicrotask()
                    break;
                }
                case REJECTED: {
                    rejectedMicrotask()
                    break;
                }
                case PENDING: {
                    this.FULFILLED_CALLBACK_LIST.push(fulfilledMicrotask)
                    this.REJECTED_CALLBACK_LIST.push(rejectedMicrotask)
                }
            }
        })
        return promise2
    }

    resolvePromise(promise2, x, resolve, reject) {
        // 如果 newPromise 和 x 指向同一对象,以 TypeError 为据因拒绝执行 newPromise
        if (promise2 === x) {
            return reject(new TypeError('The promise and the return value are the same'));
        }

        if (x instanceof MPromise) {
            // 如果 x 为 Promise ,则使 newPromise 接受 x 的状态
            // 也就是继续执行x,如果执行的时候拿到一个y,还要继续解析y
            queueMicrotask(() => {
                x.then((y) => {
                    this.resolvePromise(promise2, y, resolve, reject);
                }, reject);
            })
        } else if (typeof x === 'object' || this.isFunction(x)) {
            // 如果 x 为对象或者函数
            if (x === null) {
                // null也会被判断为对象
                return resolve(x);
            }

            let then = null;

            try {
                // 把 x.then 赋值给 then 
                // 这种首先保存 x.then 的引用,然后测试此引用,再调用此引用的处理,避免了对 x.then 属性的多次访问。这种预防措施在面对一些特殊访问器时十分重要,因为有的访问器每次访问都会导致其值的改变。
                then = x.then;
            } catch (error) {
                // 如果取 x.then 的值时抛出错误 e ,则以 e 为据因拒绝 promise
                return reject(error);
            }

            // 如果 then 是函数
            if (this.isFunction(then)) {
                let called = false;
                // 将 x 作为函数的作用域 this 调用
                // 传递两个回调函数作为参数,第一个参数叫做 resolvePromise ,第二个参数叫做 rejectPromise
                try {
                    then.call(
                        x,
                        // 如果 resolvePromise 以值 y 为参数被调用,则运行 resolvePromise
                        (y) => {
                            // 需要有一个变量called来保证只调用一次.
                            if (called) return;
                            called = true;
                            this.resolvePromise(promise2, y, resolve, reject);
                        },
                        // 如果 rejectPromise 以据因 r 为参数被调用,则以据因 r 拒绝 promise
                        (r) => {
                            if (called) return;
                            called = true;
                            reject(r);
                        });
                } catch (error) {
                    // 如果调用 then 方法抛出了异常 e:
                    if (called) return;

                    // 否则以 e 为据因拒绝 promise
                    reject(error);
                }
            } else {
                // 如果 then 不是函数,以 x 为参数执行 promise
                resolve(x);
            }
        } else {
            // 如果 x 不为对象或者函数,以 x 为参数执行 promise
            resolve(x);
        }
    }
}

const test = new MPromise((resolve, reject) => {
    setTimeout(() => {
        resolve(111);
    }, 1000);
}).then(console.log);

console.log(test);

setTimeout(() => {
    console.log(test);
}, 2000);