关于前端:手写promise

45次阅读

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

长处: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)
}

正文完
 0