SOURCE

class MyPromise {
    constructor(fn){
        this.state = "pending";
        this.value='';
        this.onResolveCallback=[];
        this.onRejectedCallback =[];
        fn(this.resolve.bind(this),this.reject.bind(this));
    }

    resolve(value){
        if(this.state==="pending"){
            this.state ="fulfilled";
            this.value = value;
            this.onResolveCallback.map(cb=>cb());
        }
    }
    reject(value){
        if(this.state==="pending"){
            this.state ="rejected";
            this.value = value;
            this.onRejectedCallback.map(cb=>cb());
        }
    }    
    then(onFulfilled,onRejected){
        if(this.state=="pending"){
            this.onResolveCallback.push(onFulfilled);
            this.onRejectedCallback.push(onRejected);
        }
        if(this.state=="fulfilled"){
            onFulfilled(this.value);
        }
        if(this.state=="rejected"){
            onRejected(this.value);
        }
    }
}

let p1 = new MyPromise((resolve,reject)=>{
    console.log(1);
    reject('reject')
    resolve('resolve')
})
p1.then((value)=>{
    console.log(value,'resolved val')
},(value)=>{
    console.log(value,'rejected val')
})
console 命令行工具 X clear

                    
>
console