Promise 작성

1869 단어 ES6promise
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)
})








좋은 웹페이지 즐겨찾기