SOURCE

const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

class MyPromise {
    constructor(executor) {
        this.value = null;
        this.reson = null;
        this.status = PENDING;
        this.onFulfilledCallbacks = [];
        this.onRejectedCallbacks = [];
        this.resolve = this.resolve.bind(this);
        this.reject = this.reject.bind(this);
        this.then = this.then.bind(this);

        executor(this.resolve, this.reject);
    }
    resolve(value) {
        if (this.status === PENDING) {
            this.status = FULFILLED;
            this.value = value;
            while (this.onFulfilledCallbacks.length > 0) {
                this.onFulfilledCallbacks.shift()(value);
            }
        }
    }
    reject(reson) {
        if (this.status === PENDING) {
            this.status = REJECTED;
            this.reson = reson;
            while (this.onRejectedCallbacks.length > 0) {
                this.onRejectedCallbacks.shift()(reson);
            }
        }
    }
    then(resolveFn, rejectFn) {
        return new MyPromise((resolve, reject) => {
            if (this.status === FULFILLED) {
                const x = resolveFn(this.value);
                if (x instanceof MyPromise) {
                    x.then(resolve, reject);
                } else {
                    resolveFn(this.value);
                }
            } else if (this.status === REJECTED) {
                reject(this.reson);
            } else {
                this.onFulfilledCallbacks.push(resolveFn);
                this.onRejectedCallbacks.push(rejectFn);
            }
        });
    }
}

new MyPromise((resolve) => {
    window.setTimeout(() => {
        resolve(2222);
    }, 3000)
}).then((value) => {
    console.log(value);
})
console 命令行工具 X clear

                    
>
console