一小段JS代码实现Deferred

这个类似于jquery的Deferred,提供reject和resolve方法。

function Deferred(){
    var self = this;
    self.promise = new Promise(function(resolve, reject){
        self._resolve = resolve;
        self._reject = reject;
    });
}

Deferred.prototype.resolve = function (data) {
    this._resolve(data);
}

Deferred.prototype.reject = function (data) {
    //this._reject.call(this.promise,data);
    this._reject(data);
}

function test() {
    var deferred = new Deferred();
    deferred.resolve(25);
    return deferred.promise;
}

test().then(function(data){
    console.log(data); //25
});

 

posted @ 2017-02-25 19:24  一片叶子啊  阅读(383)  评论(0编辑  收藏  举报