JS简单实现promise

function Promise (executor) {
    this.status = 'pending'; // 默认状态
    this.value = void 0;     // 默认值 undefined
    this.keepResolveFn = []; // 成功回调队列
    this.keepRejectFn = [];  // 失败回调队列

    const resolve = (val) => {
        this.status === 'pending' && (
            this.status = 'fulfilled',
            this.value = val,
            this.keepResolveFn.forEach(fn => fn())
        );
    };
    const reject = (val) => {
        this.status === 'pending' && (
            this.status = 'rejected',
            this.value = val,
            this.keepRejectFn.forEach(fn => fn())
        );
    };

    try {
        executor(resolve, reject); // Promise 内部立即执行executor函数
    } catch (error) {
        reject(error);
    }
}

FnPromise.prototype.then = function (onResolve, onReject) {
    this.status === 'fulfilled' && onResolve(this.value);
    this.status === 'rejected' && onReject(this.value);

    // 这一步pending状态的方案,真的佩服参考blog的作者,茅塞顿开
    this.status === 'pending' && (
        this.keepResolveFn.push(() => onResolve(this.value)),
        this.keepRejectFn.push(() => onReject(this.value))
    );

    return this; // 自动传递了Promise的状态
}
[简单实现promise](https://www.cnblogs.com/wjgoblin/p/11279081.html)
posted @ 2021-03-02 17:15  abcdefgab  阅读(197)  评论(0)    收藏  举报