一小段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 });