编辑代码

//JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
class myPromise{
    constructor(executor) {
        this.init()
        try {
            executor(this.resolve, this.resolve)
        } catch(err) {
            this.reject(err)
        }
    }

    init() {
        this.promiseState = 'pending'
        this.promiseValue = null
        this.onFulfilledList = []
        this.onRejectedList = []
        this.resolve = this.resolve.bind(this)
        this.reject = this.reject.bind(this)
    }

    resolve(value) {
        if(this.promiseState == 'pending'){
            this.promiseState = 'fulfilled'
            this.promiseValue = value
            while(this.onFulfilledList.length) {
                this.onFulfilledList.shift()(this.promiseValue)
            }
        }
    }
    reject(value) {
        if(this.promiseState == 'pending'){
            this.promiseState = 'rejected'
            this.promiseValue = value
             while(this.onRejectedList.length) {
                this.onRejectedList.shift()(this.promiseValue)
            }
        }
    }
    then(onFulfilled, onRejected) {
        // 实现链式调用
       return new myPromise((resolve, reject) => {
            const resolvePromise = cb => {
                try{
                    let x = cb(this.promiseValue)
                    if(x instanceof myPromise) {
                        x.then(resolve, reject)
                    } else {
                        resolve(x)
                    }
                }catch(error) {
                    reject(error)
                }
            }
            if(this.promiseState == 'fulfilled') {
                resolvePromise(onFulfilled)
            } else if (this.promiseState == 'rejected') {
                resolvePromise(onRejected)
            } else if (this.promiseState == 'pending') {
                this.onFulfilledList.push(resolvePromise.bind(this, onFulfilled))
                this.onRejectedList.push(resolvePromise.bind(this, onRejected))
            }
        })
    }
}
console.log('start')
const p1 = new myPromise((resolve, reject) => {
   console.log('1')
   resolve('succ')
}).then(res => new myPromise((resolve, reject)=> resolve(res + '333')))
.then((res) => {
    console.log(res)
})
setTimeout(() => {
   console.log('2')
},0)
console.log('end')