Promise的实现

class Promise {
    constructor(executor) {
        this.status = 'pending';
        this.value = undefined;
        this.reason = undefined;
        //存放成功的回调
        this.onFulFilledCallbacks = [];
        //存放失败的回调
        this.onRejectedCallbacks = [];

        let resolve = (value) => {
            if (this.status == 'pending') {
                this.status = 'fulfilled';
                this.value = value;
                this.onFulFilledCallbacks.forEach(fn => fn())
            }
        }

        let reject = (err) => {
            if (this.status == 'pending') {
                this.status = 'rejected';
                this.reason = err;
                this.onRejectedCallbacks.forEach(fn => fn())
            }
        }

        try {
            executor(resolve, reject)
        } catch (e) {
            reject(e)
        }

    }

    then(onFulFilled, onRejected) {
        let promise2
        if (this.status = 'fulfilled') {
            promise2 = new Promise((resolve, reject) => {
                let x = onFulFilled(this.value);
                //解析promise2和x之间的关系
                resolvePromise(promise2, x, resolve, reject)
            })
        }
        if (this.status = 'rejected') {
            promise2 = new Promise((resolve, reject) => {
                let x = onRejected(this.reason);
                resolvePromise(promise2, x, resolve, reject)
            })
        }
        //异步调用时进不到resolve,状态始终为pending,此时可以先把callback存起来待到resolve或reject再逐一执行
        if (this.status = 'pending') {
            this.onFulFilledCallbacks.push(() => {
                promise2 = new Promise((resolve, reject) => {
                    let x = onFulFilled(this.value)
                    resolvePromise(promise2, x, resolve, reject)
                })
            })
            this.onRejectedCallbacks.push(() => {
                promise2 = new Promise((resolve, reject) => {
                    let x = onRejected(this.reason)
                    resolvePromise(promise2, x, resolve, reject)
                })
            })
        }
        return promise2;
    }
}

//判断x是不是promise,规范规定代码确定不同的promise间可以交互。
resolvePromise(promise2, x, resolve, reject) {
    if (x === promise2) {
        return reject(new TypeError('Chaining cycle detected for promise!'))
    }
    if (x !== null && typeof x == 'object' || typeof x == 'function') {
        //防止取then时出现异常 Object.definedProperty
        try {
            if (typeof x == 'function') {
                x.then.call(x, y => {
                    resolvePromise(promise2, y, resolve, reject)
                })
            } else {
                resolve(x)
            }
        } catch (e) {
            reject(e)
        }
    } else {
        resolve(x)
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 近期去面试,有道题很有意思,实现一个 promise。奈于心里素质差了,又紧张,没想出来。结束后方才想起,故记录一...
    大香蕉s阅读 666评论 0 2
  • 自从有了promise,我写异步代码就是一个then,then的层级深了就是一个async,包治百病,哈哈哈哈。。...
    blossom_绽放阅读 615评论 0 1
  • 排版很不友好,抱歉 /* * 实现Promise是根据Promise规范来的:https://promisesap...
    Egde阅读 1,509评论 0 0
  • 今天实现以下如何实现promise的实现。为什么出现这个点。大家肯定都知道。就是所谓的'回掉地狱'。就是函数里面不...
    小小小小的人头阅读 415评论 0 1
  • promise 在完成符合Promis/A+规范之前,我们可以实现一个简易版Promise,因为在面试中,如果你能...
    豆芽y_阅读 1,096评论 0 14