博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
20170626-Promise的实现
阅读量:6290 次
发布时间:2019-06-22

本文共 1019 字,大约阅读时间需要 3 分钟。

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)

转载地址:http://rgkta.baihongyu.com/

你可能感兴趣的文章