2

Promise的实现

class Promise111{
    constructor(){
        this.callbacks = []
        this.oncatch = null
    }
    then(onSuccess, onFail){
        this.callbacks.push({
            resolve: onSuccess,
            reject: onFail
        })
        return this
    }
    resolve(result){
        this.complete('resolve', result)
    }
    reject(result){
        this.complete('reject', result)
    }
    complete(type, result){
        if(type === 'reject' && this.oncatch){
            this.callbacks = []
            this.oncatch(result)
        } else {
            let callbackObj = this.callbacks.shift()
            callbackObj[type](result)
        }
    }
    catch(onFail){
        this.oncatch = onFail
        return this
    }
}
  • 测试

var p = new Promise111()

function fn(){
    setTimeout(function(){
        p.resolve('data1')
    }, 1000)
    return p
}

function fn1(result){
    console.log('fn1', result)
    setTimeout(function(){
        p.resolve('data2')
    }, 2000)
}

function fn2(result){
    console.log('fn2', result)
}

fn().then(fn1).then(fn2)

jhhfft
590 声望40 粉丝

Write the Code. Change the World.