Skip to content

Instantly share code, notes, and snippets.

@antillas21
Created October 4, 2013 20:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antillas21/6832001 to your computer and use it in GitHub Desktop.
Save antillas21/6832001 to your computer and use it in GitHub Desktop.
Basic JS Deferred object implementation
/*
** Solution proposed by: Chad Elliott (https://www.vizify.com/thethechad)
** at StackOverflow. Link to original: http://stackoverflow.com/a/18097040
*/
function Deferred(){
this._done = [];
this._fail = [];
}
Deferred.prototype = {
execute: function(list, args){
var i = list.length;
// convert arguments to an array
// so they can be sent to the
// callbacks via the apply method
args = Array.prototype.slice.call(args);
while(i--) list[i].apply(null, args);
},
resolve: function(){
this.execute(this._done, arguments);
},
reject: function(){
this.execute(this._fail, arguments);
},
done: function(callback){
this._done.push(callback);
},
fail: function(callback){
this._fail.push(callback);
}
}
/*
** Usage example
*/
var v;
var setVal = function() {
var d = new Deferred();
setTimeout(function() {
v = 'a value';
d.resolve(this);
}, 5000);
return d;
};
setVal().done(function() {
console.log('all done :' + v);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment