优点:1.支持链式调用,可以解决回调地狱问题

export default function Promise(executor) {
    this.PromiseState = 'pending'
    this.PromiseResult = null
    this.callbacks = []
    const self = this
    function resolve(data) {
        if (self.PromiseState !== 'pending') return//不可重复更改状态
        self.PromiseState = 'fulfilled' //修改状态
        self.PromiseResult = data//结果赋值
        //异步函数执行回调函数
        setTimeout(()=>{
            self.callbacks.forEach(item => {
                item.onResolved(data)
                })
        })
        
    }
    function reject(data) {
        if (self.PromiseState !== 'pending') return
        self.PromiseState = 'rejected'
        self.PromiseResult = data
        setTimeout(()=>{
            self.callbacks.forEach(item => {
                item.onRejected(data)
                })
        })
       
    }
    try {
        executor(resolve, reject)
    } catch (error) {
        console.log('err' + error)
        reject(error)
    }

    return executor(resolve, reject)
}

Promise.prototype.then = function (onResolved, onRejected) {
    const self = this
    if(typeof onRejected !=='function'){
        onRejected = reason =>{
            throw reason
        }
    }
    if(typeof onResolved!=='function'){
        onResolved = value =>value
    }
    return new Promise((resolve, reject) => {
        function callback(type) {
            try {
                let result = type(self.PromiseResult)
                if (result instanceof Promise) {
                    result.then(v => {
                        resolve(v)
                    }, r => {
                        resolve(r)
                    })
                } else {
                    resolve(result)
                }
            } catch (e) {
                reject(e)
            }
        }
        if (this.PromiseState === 'fulfilled') {
            callback(onResolved)
        } else if (this.PromiseState === 'rejected') {
            callback(onRejected)
        } else if (this.PromiseState === 'pending') {
            //异步调用时,在改变状态后执行函数
            this.callbacks.push({
                onResolved: function () {
                    setTimeout(()=>{
                      callback(onResolved)
                    })
                   
                },
                onRejected: function () {
                    setTimeout(()=>{
                      callback(onRejected)
                    })
                }
            })
        }
    })
}

Promise.prototype.catch = function(onRejected){
    return this.then(undefined,onRejected)
}

ohoherror
21 声望1 粉丝