编辑代码

// class 版 - 简单手写Promsie

class _Promise {
    constructor(callback) {
        this.state = "PENDING"
        this.result = "null"
        this.tasks = []

        const resolve = (result) => {
            // 如果是一个 _promise 对象,就处理一下,后续的逻辑不关它事,跳过
            if (result instanceof _Promise) {
                result.then(resolve)
                return;
            }

            // 数据回来了,成功调用 resolve,
            this.state = "FULFILLED"
            this.result = result

            this.tasks.forEach(cb => {
                this.handler(cb)
            })
        }

        callback(resolve)
    }

    // 中间层: 处理逻辑的
    handler(cb) {
        // 数据还没回来,先用户交待的处理任务先存储起来
        if (this.state === "PENDING") {
            this.tasks.push(cb)
            return;
        }

        // then 没有参数,直接 resolve
        if (!cb.onFulfilled) {
            cb.resolve()
        }

        // 数据回来了,执行任务交待的处理函数,如果有
        const ret = cb.onFulfilled(this.result)
        cb.resolve(ret)
    }

    then(onFulfilled) {
        // 链式then本质是返回新的promise对象
        return new _Promise((resolve) => {
            this.handler({
                onFulfilled,
                resolve
            })
        })
    }
}


new _Promise(resolve => {
    console.log(1)
    setTimeout(resolve, 10, 2)
})
.then(res => {
    console.log(res)
    return new _Promise(resolve => {
        console.log(3)
        setTimeout(resolve, 10, 4)
    })
})
.then(res => console.log(res))