MyPromise

class MyPromise{
    constructor(executor){
        this.state='pending';
        this.value=undefined;
        this.reason=undefined;
        this.onFulfilledCallbacks=[];
        this.onRejectedCallbacks=[];
           // 绑定 this,确保 resolve/reject 中的 this 指向实例
        this.resolve = this.resolve.bind(this);
        this.reject = this.reject.bind(this);
        
        try {
            executor(this.resolve, this.reject);
        } catch (error) {
            this.reject(error);
        }
    }
    resolve(value){
        if(this.state==='pending'){
            this.state='fulfilled';
            this.value=value;
            this.onFulfilledCallbacks.forEach(callback=>{
                setTimeout(()=>{
                    callback(this.value);
                },0)
            })
        }
    }
    reject(reason){
          if(this.state==='pending'){
            this.state='rejected';
            this.reason=reason;
            this.onRejectedCallbacks.forEach(callback=>{
                setTimeout(()=>{
                    callback(this.reason);
                },0)
            })
        }
    }
    then(onfulfiled,onrejected){
        onfulfiled=typeof onfulfiled==='function'?onfulfiled:(value)=>value;
        onrejected=typeof onrejected==='function'?onrejected:(reason)=>{throw reason};
        return new MyPromise((resolve,reject)=>{
            const handleFulfilled=(value)=>{
                try{
                    const result=onfulfiled(value);
                    resolve(result);
                }catch(error){
                    reject(error)
                }
            }
            const handleRejected=(reason)=>{
                try{
                    const result=onrejected(reason);
                    resolve(result);
                }catch(error){
                    reject(error)
                }
            }
            if(this.state==='fulfilled'){
                setTimeout(()=>{handleFulfilled(this.value)},0)
            }else if(this.state==='rejected'){
                setTimeout(()=>{handleRejected(this.reason)},0)
            }else{
                this.onFulfilledCallbacks.push(()=>{
                    setTimeout(()=>{handleFulfilled(this.value)},0)
                })
                this.onRejectedCallbacks.push(()=>{
                    setTimeout(()=>{handleRejected(this.reason)},0)
                })
            }
        })
    }
    catch(onRejected){
        return this.then(null,onRejected);
    }
    finally(onFinally){
         return this.then(
            value => MyPromise.resolve(onFinally()).then(() => value),
            reason => MyPromise.resolve(onFinally()).then(() => { throw reason })
        );
    }
    static resolve(value) {
        if (value instanceof MyPromise) {
            return value;
        }
        return new MyPromise(resolve => resolve(value));
    };
    static reject(reason) {
        return new MyPromise(null,reject => reject(reason));
    };
    // 添加 all 方法
    static all(promises) {
        return new MyPromise((resolve, reject) => {
            if (!Array.isArray(promises)) {
                return reject(new TypeError('Argument must be an array'));
            }
            
            if (promises.length === 0) {
                return resolve([]);
            }
            
            const results = [];
            let completedCount = 0;
            
            promises.forEach((promise, index) => {
                MyPromise.resolve(promise).then(
                    value => {
                        results[index] = value;
                        completedCount++;
                        
                        if (completedCount === promises.length) {
                            resolve(results);
                        }
                    },
                    reject
                );
            });
        });
    }
    
    // 添加 race 方法
    static race(promises) {
        return new MyPromise((resolve, reject) => {
            if (!Array.isArray(promises)) {
                return reject(new TypeError('Argument must be an array'));
            }
            
            promises.forEach(promise => {
                MyPromise.resolve(promise).then(resolve, reject);
            });
        });
    }
}

 

posted @ 2025-11-26 11:45  howhy  阅读(3)  评论(0)    收藏  举报