手写一个promise


class Qromise {
    constructor(fn) {
        this.status = 'pending'
        this.error = ''
        this.data = ''
        try{
            fn(this.onFullfilled.bind(this), this.onRejected.bind(this))
        }catch(e){
            this.reject(e)
        }
    }
    then(fn) {
        if( this.status === 'Fullfilled' ) {
            fn.call(this, this.data)
        }
        return this
    }
    reject(fn) {
        if( this.status === 'Rejected' ) {
            fn.call(this, this.error)
        }
        return this
    } 
    onFullfilled(data) {
        console.log('on fullfilled')
        this.data = data
        this.status = 'Fullfilled'
    }
    onRejected(err) {
        console.log('on rejected')
        this.error = err
        this.status = 'Rejected'
    }
}

module.exports = Qromise

猜你喜欢

转载自blog.csdn.net/weixin_40821790/article/details/81185812