Skip to content

Instantly share code, notes, and snippets.

@srhyne
Created August 6, 2018 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srhyne/f03e86eda73e4ca93658406e73f67a0e to your computer and use it in GitHub Desktop.
Save srhyne/f03e86eda73e4ca93658406e73f67a0e to your computer and use it in GitHub Desktop.
$.Deferred Alternative using Promises
function Deferred( executor ){
var self = this;
this._promise = new Promise(function(resolve, reject){
self._resolver = resolve;
self._rejector = reject;
if( typeof executor === 'function' ){
executor(resolve, rejector)
}
});
}
Deferred.all = function(deferreds){
var promises = deferreds.map(function(d){
return d.promise();
});
return Promise.all(promises)
}
Object.assign(Deferred.prototype, {
promise : function(){
return this._promise;
},
//returns promise
then : function(cb){
return this._promise.then(cb);
},
//returns promise
catch : function(){
return this._promise.catch(cb);
},
finally : function(){
return this._promise.finally(cb);
},
//returns Deferred
done : function(cb){
this._promise.then(cb);
return this;
},
//returns Deferred
fail : function(cb){
this._promise.catch(cb);
return this;
},
resolve : function(value){
this.resolved = true;
this._resolver(value);
return this;
},
reject : function(){
this._rejector(value)
return this;
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment