美文网首页
实现promise 代码

实现promise 代码

作者: aaagu1234 | 来源:发表于2021-10-27 14:36 被阅读0次
    const STATUS = {
        PENDING: 'pending',
        FULFILLED: 'fulFilled',
        REJECTED: 'rejected'
    }
    
    class MyPromise {
        constructor(executor) {
            this.status = STATUS.PENDING    // 状态值
            this.value = undefined          // 成功返回值
            this.reason = undefined         // 失败返回值
            this.onFulFilledCallbacks = []  // 成功回调执行队列----up
            this.onRejectedCallbacks = []   // 失败回调执行队列----up
    
            // 成功
            const resolve = (val) => {
                // PENDING用来屏蔽的,resolve和reject只能调用一个,不能同时调用
                if (this.status === STATUS.PENDING) {
                    this.status = STATUS.FULFILLED
                    this.value = val
                    this.onFulFilledCallbacks.forEach(fn => fn())   // ----up
                }
            }
            // 是失败
            const reject = (reason) => {
                if (this.status === STATUS.PENDING) {
                    this.status = STATUS.REJECTED
                    this.reason = reason
                    this.onRejectedCallbacks.forEach(fn => fn())   // ----up
                }
            }
    
            try {
                executor(resolve, reject)
            } catch (e) {
                reject(e)
            }
        }
    
        then(onFullFilled, onRejected) {
            // 同步调用判断
            if (this.status === STATUS.FULFILLED) {
                onFullFilled(this.value)
            }
            if (this.status === STATUS.REJECTED) {
                onRejected(this.reason)
            }
            // 异步调用判断 ----up
            if (this.status === STATUS.PENDING) {
                this.onFulFilledCallbacks.push(() => {
                    onFullFilled(this.value)
                })
                this.onRejectedCallbacks.push(() => {
                    onRejected(this.reason)
                })
            }
        }
    }
    
    // const p = new MyPromise((resolve, reject) => {
    //     // resolve('success')   // 走了成功就不会走失败了
    //     // throw new Error('失败') // 失败了就走resolve
    //     // reject('failed')       // 走了失败就不会走成功
    //     resolve('成功!')
    // })
    // p.then((res) => {
    //     console.log(res)
    // }, (err) => {
    //     console.log(err)
    // })
    
    const p = new MyPromise((resolve, reject) => {
        setTimeout(function() {
            resolve('success')
        }, 1000)
    })
    p.then((res) => {
        console.log(res)
    }, (err) => {
        console.log(err)
    })
    
    

    参考: https://blog.csdn.net/qq_37820580/article/details/110528932

    相关文章

      网友评论

          本文标题:实现promise 代码

          本文链接:https://www.haomeiwen.com/subject/alhpaltx.html