Skip to content

Instantly share code, notes, and snippets.

@adrianvlupu
Created July 23, 2014 09:46
Show Gist options
  • Save adrianvlupu/f71f0720063c62fa9faa to your computer and use it in GitHub Desktop.
Save adrianvlupu/f71f0720063c62fa9faa to your computer and use it in GitHub Desktop.
deferred object js
var $d = (function () {
function $d() {
var self = this;
this._success = [];
this._fail = [];
this.promise = {
then: function (callback) {
self._success.push(callback);
},
fail: function(callback){
self._done.push(callback);
}
};
}
$d.prototype = {
execute: function (list, args) {
var i = list.length;
args = Array.prototype.slice.call(args);
while (i--) list[i].apply(null, args);
},
resolve: function () {
this.execute(this._success, arguments);
},
reject: function () {
this.execute(this._fail, arguments);
}
};
return $d
}) ();
//API Method
var getStuff = function () {
var d = new $d();
//mare ajax
setTimeout(function () {
d.resolve('Explosions');
}, 1000);
//return a promise
return d.promise;
};
getStuff().then(function (data) {
console.log('BOOM ' + data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment