SOURCE

// 定义三种状态
const PENDING = 'pending';
const REJECTED = 'rejected';
const FULFILLED = 'fulfilled';

class myPromise {
    // 传入执行器函数
    constructor(executor) {
        this.status = PENDING;
        this.value = undefined;
        this.reason = undefined;

        // 存储onFulfilled,onRejected回调数组
        this.onFulfilledCallbacks = []
        this.onRejectedCallbacks = []

        const resolve = value => {
            // 状态不可逆
            if (this.status == PENDING) {
                this.status = FULFILLED
                this.value = value;

                // 依次执行onFulfilledCallbacks里的回调
                this.onFulfilledCallbacks.forEach(callback => callback(value))
            }
        }

        const reject = reason => {
            if (this.status == PENDING) {
                this.status = REJECTED;
                this.reason = reason;

                // 依次执行onRejectedCallbacks里的回调
                this.onRejectedCallbacks.forEach(callback => callback(reason))
            }
        }

        // 抛出异常
        try {
            executor(resolve, reject)
        } catch (err) {
            reject(err)
        }
    }

    then(onFulfilled, onRejected) {
        // 判断是否函数,否:就赋值一个函数返回value
        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value
        onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason }

        // 判断状态, 回调传入value
        if (this.status === FULFILLED) onFulfilled(this.value)
        if (this.status === REJECTED) onRejected(this.reason)

        // 如果是异步函数此时状态还未改变
        if (this.status === PENDING) {
            this.onFulfilledCallbacks.push(onFulfilled.bind(this))
            this.onRejectedCallbacks.push(onRejected.bind(this))
        }
    }
}

const p = new myPromise((resove, reject) => {
    resove('success')
    reject('err')
})
p.then(reason => console.log(reason))

const p1 = new myPromise((resolve, reject) => {
    // 异步操作代码
    setTimeout(() => {
        const rand = Math.random() * 100
        if (rand >= 50) {
            // 成功时执行
            resolve('success')
        } else {
            // 失败时执行
            reject('error')
        }
    }, 1000)

})
p1.then(res=>console.log(res))
console 命令行工具 X clear

                    
>
console