Skip to content

Instantly share code, notes, and snippets.

@beckyconning
Last active August 29, 2015 14:00
Show Gist options
  • Save beckyconning/11205455 to your computer and use it in GitHub Desktop.
Save beckyconning/11205455 to your computer and use it in GitHub Desktop.
// so this is a basic deferred
var Promise = function() {
this.successCallbacks = [];
this.failCallbacks = [];
};
Promise.prototype.then = function(successCallback, failCallback) {
if (successCallback) this.successCallbacks.push(successCallback);
if (failCallback) this.failCallbacks.push(failCallback);
};
var Deferred = function() {
this.promise = new Promise();
};
Deferred.prototype.resolve = function(value) {
this.promise.successCallbacks.forEach(function(callback) {
callback(value);
});
};
Deferred.prototype.reject = function(value) {
this.promise.failCallbacks.forEach(function(callback) {
callback(value);
});
};
// okay so i think thats right now, and we'd use it like this
var waitFiveSeconds = function() {
var fiveSecondDeferred = new Deferred();
var fiveSecondTimeout = setTimeout(function() {
fiveSecondDeferred.resolve('its been like five seconds');
}, 5000);
return fiveSecondDeferred.promise;
};
waitFiveSeconds().then(function(message) {
console.log('moooo~');
console.log(message);
});
console.log('cows say... ');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment