Handwritten achieve a 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 (fulfiil, 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 = NewPromise(function (resolve, reject) {

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







 

Published 81 original articles · won praise 62 · views 70000 +

Guess you like

Origin blog.csdn.net/qq_38021852/article/details/89156707