SOURCE

let pending = 'pending'
let success = 'success'
let fail = 'fail'

// exe 实例化对象执行函数对象
function PromiseM(exe){
    let _this = this
    let state = pending
    let value = undefined
    let reason = undefined

    this.onSuccess = []
    this.onFail = []

    function resolve(value){
        if(_this.state == pending){
            _this.value=value
            _this.state=success
            _this.onSuccess.forEach(fn => fn(value))
        }
    }

    function reject(reason){
        if(this.state == pending){
            _this.reason=reason
            _this.state=fail
            _this.onFail.forEach(fn => fn(reason))
        }
    }

    try{
        exe(resolve,reject)
    }catch(e){
        reject(e)
    }
}

PromiseM.prototype.then = function(onSuccess,onFail){
    if(typeof(onSuccess) === 'function'&&this.state==success){
        onSuccess(this.value)
    }
    if(typeof(onFail) === 'function'&&this.state==fail){
        onSuccess(this.reason)
    }
    if(this.state==pending){
        typeof onSuccess === 'function' && this.onSuccess.push(onSuccess)
        typeof onFail === 'function' && this.onFail.push(onFail)
    }
}

var p = new PromiseM((resolve,reject)=>{
    // 同步调用
    // resolve(1)

    // 实现异步调用
    setTimeout(()=>{
        resolve(2)
    },0)
})

p.then(res=>{
    console.log(res,'res')
}).catch(err=>{
    console.log(err,'err')
})

console 命令行工具 X clear

                    
>
console