SOURCE

// 注意事项:

// Promise要暴露then/catch方法

// Promise构造函数接收一个立即执行的函数callback

// then/catch只负责把回调放入数组即可

// resolve/reject负责执行

// resolve/reject 需要添加宏任务(setTimeout)

function Pro(callback) {
    // 设置三种状态
    const pending = 'pending'
    const fulfilled = 'fullfilled'
    const rejected = 'rejected'
    // 当前状态
    this.state = pending
    // 当前值
    this.value = null
    // 失败原因
    this.reason = null

    // 定义成功和失败的数组
    this.fullfiledCallback = []
    this.rejectedCallback = []

    // 成功处理
    this.resolve = data => {
        setTimeout(() => {
            if (this.state == pending) {
                this.state = fulfilled
                this.value = data
                this.fullfiledCallback.map(fn => fn(this.value))
            }
        })
    }

    // 失败处理
    this.reject = reason => {
        setTimeout(() => {
            if (this.state == pending) {
                this.state = rejected
                this.reason = reason
                this.rejectedCallback.map(fn => fn(this.reason))
            }
        })
    }

    // 捕获成功或失败, 扔到成功和失败数组
    this.then = function (successFn, errorFn) {
        this.fullfiledCallback.push(successFn)
        this.rejectedCallback.push(errorFn)
    }

    this.catch = (errorFn) => {
        this.rejectedCallback.push(errorFn)
    }
    callback(this.resolve, this.reject)
}



// 验证结果
new Pro((resolve,reject)=>{
    setTimeout(()=>{resolve([1,2,3]);},1000)
}).then((data)=>{
    console.log(data);
},(error)=>{
    console.log(error);
})
console 命令行工具 X clear

                    
>
console