const Promise = function(fn){
    let state = {
        pending: "pending",
        fulfilled: "fulfilled",
        rejected: "rejected"
    }
    let chain = {
        status: state.pending
    }
    let result;
    chain.then = function(fn){
        if( state.fulfilled === chain.status ){
            result = fn(result)
            if(typeof result === "object" && result.constructor === Promise) return result;
      }
        return chain
    }
    chain.catch = function(fn){
        if( state.rejected === chain.status ){
            result = fn(result)
            if(typeof result === "object" && result.constructor === Promise) return result;
        }
        return chain
    }
    this.then = chain.then
    this.catch = chain.catch

    function resolve(val){
        if(chain.status !== state.pending) return;
        chain.status = state.fulfilled
        result = val
    }
    function reject(val){
        if(chain.status !== state.pending) return;
        chain.status = state.rejected
        result = val
    }
    fn(resolve, reject)
}

版权声明:本文为webmagic原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/webmagic/p/8623329.html