简单的 Promise 实现 一

时间:2024-07-23 23:38:08
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)
}

简单的 Promise 实现 一