首页 > 试题广场 >

简单的实现一个promise

[问答题]
    function NewPromise(fn){
        this.state = 'PENDING'
        this.fulfillList = []
        this.rejectList = []
        fn(this.resolve.bind(this),this.reject.bind(this))
    }
    //成功,执行成功队列的函数
    NewPromise.prototype.resolve = function(data){
        this.state = 'FULFILLED'
        var args = [].slice.call(arguments)
        setTimeout(function () {
            this.fulfillList.forEach(function (itemFn,key,arr) {
                itemFn.apply(null,args)
                arr.shift()
            })
        }.bind(this),0)
    }
    //失败,执行失败队列的函数
    NewPromise.prototype.reject = function(data){
        this.state = 'REJECTED'
        var args2 = [].slice.call(arguments)
        setTimeout(function () {
            this.rejectList.forEach(function (itemFn,key,arr) {
                itemFn.apply(null,args2)
                arr.shift()
            })
        }.bind(this),0)
    }
    //成功回调函数
    NewPromise.prototype.done = function(handle){
        if(typeof handle === 'function')
            this.fulfillList.push(handle)
        else
            throw new Error('回调函数出错')
        return this
    }
    //失败回调函数
    NewPromise.prototype.fail = function(handle){
        if(typeof handle === 'function')
            this.rejectList.push(handle)
        else
            throw new Error('回调函数出错')
        return this
    }
    //失败成功写在一个方法内
    NewPromise.prototype.then = function(fulfill,reject){
        this.done(fulfill)||function () {}
            .fail(reject)||function () {}
        return this
    }
    //失败成功都执行一个函数
    NewPromise.prototype.always = function(handle){
        this.done(handle)||function () {}
            .fail(handle)||function () {}
        return this
    }

    var prm = new NewPromise(function (resolve,reject) {
        setTimeout(function(){
            resolve('成功的参数')
            reject('失败的参数')
        },1000)
    })
    prm.then(function(data){
        console.log(data)
    }).fail(function(data){
        console.log(data)
    })

发表于 2019-03-15 21:01:39 回复(0)
new Proimise(  (res, rej)  => {
    if (res) {
        
    } else {
        //  走reject
    }
}).then(
    //  callback()
    console.error(e)
)
发表于 2019-03-01 17:36:02 回复(0)
监听异步操作的前一段结果,如果结果变化执行回调
发表于 2019-02-12 00:24:01 回复(0)
https://juejin.im/entry/58a10aa61b69e60059d1d2af
发表于 2019-01-17 23:10:30 回复(0)
new Promise((resolve,reject)=>{if(){resolve}else{reject}).then(callback)
发表于 2018-12-20 09:38:40 回复(0)