Last active
August 29, 2015 14:00
-
-
Save beckyconning/11205455 to your computer and use it in GitHub Desktop.
This file contains 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
// 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