20170626-Promise的完成

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
    原文地址: https://segmentfault.com/a/1190000009938464
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞