手写Promise

如何使用promise

const p1 = new Promise((resolve, reject) = {
    执行一个任务
    成功了调用resolve()
    失败了调用reject()
})
p1.then(s1, e1)

当调用resolve()之后会调用s1

当失败了调用reject()会调用e1

手写Promise

class Promise2 {
    quene1 = []
    quene2 = []

    constructor(fn) {
        const resolve = (data) => {
            setTimeout(() => {
                for (let i = 0; i <= quene1.length; i++) {
                    this.quene1[i](data)
                }
            })
        }
        const reject = (data) => {
            setTimeout(() => {
                for (let i = 0; i <= this.quene2.length; i++) {
                    this.quene2[i](data)
                }
            })
        }
        fn(resolve, reject)
    }

    then(s, e) {
        this.quene1.push(s)
        this.quene2.push(e)
        return this
    }
}

你可能感兴趣的