Created
July 23, 2014 09:46
-
-
Save adrianvlupu/f71f0720063c62fa9faa to your computer and use it in GitHub Desktop.
deferred object js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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