手写实现简易版Promise

37次阅读

共计 1239 个字符,预计需要花费 4 分钟才能阅读完成。

//1. 定义三种状态
const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'
function MyPromisr(fn){
       // 重命名 this,防止接下来找不到正确的 this
       const that = this
       that.state = PENDING // 初始状态为等待
       that.value = null //value 用于保存 resolved 或 rejoiced 传入的值
       that.resolvedCallbacks = [] // 成功请求后的回调数组
       // 定义完成的回调函数
       function resolved(value) {
            // 只有在等待状态才可以改变状态
            if (that.state === PENDING) {
                that.state = RESOLVED
                that.value = value
                that.resolvedCallbacks.map(cb => cb(that.value))
            }
        }
        // 定义拒绝的回调函数
        function rejected(value) {
            // 只有在等待状态才可以改变状态
            if (that.state === PENDING) {
                that.state = REJECTED
                that.value = value
                that.rejectedCallbacks.map(cb => cb(that.value))
            }
        }
        // 定义了两种状态的回调函数后, 执行 mypromise 传参的函数
        try {fn(resolved,rejected)
        } catch (e) {rejected(e)
        }
}
// 定义 then
MyPromise.prototype.then = function(onFulfilled,onRejected){
    const that = this
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled :v => v
    onRejected = 
     typeof onRejected === 'function'
        ? onRejected
        : r => {throw r}
    if (that.state === PENDING) {that.resolvedCallbacks.push(onFulfilled)
        that.rejectedCallbacks.push(onRejected)
    }
    if (that.state === RESOLVED) {onFulfilled(that.value)
    }
    // console.log(that.state,'has change')
    if (that.state === REJECTED) {onRejected(that.value)
    }
}

// 调用
new MyPromise((resolved,rejected) => {setTimeout(()=>{resolved(1)
        rejected(2)
    },0)
}).then(value=>{console.log(value)
},value=>{console.log(value)
})

正文完
 0