JS Promise的简单实现

//constructor
var Promise = function() {
    this.callbacks = [];
}


Promise.prototype = {
    construct: Promise,
    resolve: function(result) {
        this.complete("resolve", result);
    },


    reject: function(result) {
        this.complete("reject", result);
    },


    complete: function(type, result) {
        while (this.callbacks[0]) {
            this.callbacks.shift()[type](result);
        }
    },


    then: function(successHandler, failedHandler) {
        this.callbacks.push({
            resolve: successHandler,
            reject: failedHandler
        });


        return this;
    }
}


// test
var promise = new Promise();

你可能感兴趣的:(js)