SOURCE


class wjPromise{

    status = 'pending';
    result;
    reason;
    onResolvedArr = [];
    onRejectedArr = [];

    constructor(fn){
        const resolve = (result) => {
           if(this.status === 'pending'){
                this.result = result;
                this.status = 'resolved';
                this.onResolvedArr.map((fn) =>fn())
           }
        }
        const rejected = (reason) =>{
            if(this.status === 'pending'){
                this.reason = reason;
                this.status = 'rejected'
                this.onRejectedArr.map((fn) =>fn())
            }
        }
        fn(resolve,rejected)
    }
    then(onResolved,onRejected){

        onResolved = typeof onResolved === 'function' ? onResolved : (data)=>data;
        onRejected = typeof onRejected === 'function' ? onRejected : (data)=>data;

        return new wjPromise((resolve,reject)=>{
            if(this.status === 'resolved'){
                setTimeout(()=>{
                        onResolved(this.result)
                },0)
                }

                if(this.status === 'rejected'){
                    setTimeout(() =>{
                        onRejected(this.reason);
                    },0)
                }

                if(this.status === 'pending'){
                    this.onResolvedArr.push(()=>{
                        onResolved(this.result)
                    })
                    this.onResolvedArr.push(()=>{
                        onRejected(this.reason)
                    })
                 }
        })
       
    }
}

 

new wjPromise((resolve,reject)=>{
    setTimeout(()=>{
        resolve('aaa');
    },1000)
    console.log('arrr')
}).then(res =>{
    console.log(res)
    console.log('resolved')
    // return 'abc'
})
console.log('abcdefg')
console 命令行工具 X clear

                    
>
console