跟着NONO-简单的一个手写promise

44 阅读1分钟
class MyPromise{
    constructor(callback){
        this.status = 'pending';
        this.value = undefined;
        this.reason = undefined;
        this.onResolvedCallbacks = [];
        this.onRejectedCallbacks = [];

        // 定义 resolve
        const resolve = value => {
            if(this.status === 'pending'){
                this.status = 'resolved';
                this.value = value;
                this.onResolvedCallbacks.forEach(cb => cb());
            }
        }
        
        // 定义 reject
        const reject = reason => {
            if(this.status === 'pending'){
                this.status = 'rejected';
                this.reason = this.reason;
                this.onRejectedCallbacks.forEach(cb => cb());
            }
        }

        callback(resolve, reject);
    }

    then(onResolved, onRejected){
        const newPromise = new MyPromise((resolve, reject) => {
            if(this.status === 'resolved') {
                try {
                    const x = onResolved(this.value);
                    resolve(x)
                } catch (error) {
                    reject(error)
                }
            }

            if(this.status === 'rejected') {
                try {
                    const x = onRejected(this.reason);
                    resolve(x)
                } catch (error) {
                    reject(error)
                }
            }

            if(this.status === 'pending') {
                this.onResolvedCallbacks.push(()=>{
                    try {
                        const x = onResolved(this.value);
                        resolve(x)
                    } catch (error) {
                        reject(error)
                    }
                })
                this.onRejectedCallbacks.push(()=>{
                    try {
                        const x = onRejected(this.reason);
                        resolve(x)
                    } catch (error) {
                        reject(err)
                    }
                })
            }
        })
        return newPromise
    }

    catch(onRejected){
        return this.then(null, onRejected);
    }
};