JS Promise原理

class MyPromise2 {
    constructor(executor) {
        this.state = "pending"
        this.value = undefined
        this.reason = undefined
        this.successCB = []
        this.failCB = []

        let resolve = (value) => {
            if(this.state === "pending") {
                this.state = "fulfilled"
                this.value = value
                this.successCB.forEach(f => f())
            }
        }
        let reject = (reason) => {
            if(this.state === "pending") {
                this.state = "rejected"
                this.value = value
                this.failCB.forEach(f => f())
            }
        }
        try {
            executor(resolve, reject)
        } catch (error) {
            reject(error)
        }
    }
    then(onFulfillled, onRejected) {
        if(this.state === "fulfilled") {
            onFulfillled(this.value)
        }
        if(this.state === "rejected") {
            onRejected(this.value)
        }
        if(this.state === "pending") {
            this.successCB.push(()=>{
                onRejected(this.value)
            })
            this.failCB.push(()=> {
                onRejected(this.reason)
            })
        }
    }
}
Promise.all = function(promises) {
    let list = []
    let count = 0
    function handle(i, data) {
        list[i] = data
        count++
        if(count = promises.length) {
            resolve(list)
        }
    }
    return Promise((resolve, reject) =>{
        for(let i = 0; i < promises.length; i++) {
            promises[i].then(res=>{
                handle(i, res)
            }, err => reject(err))
        }
    })
}

你可能感兴趣的:(JS手写题,javascript,前端,开发语言)