Created
June 7, 2014 15:18
-
-
Save flaki/f7c0567b5e104c136dbd to your computer and use it in GitHub Desktop.
Deferred objects tooling based on the native ES6 Promise implementation
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
/* | |
* Extends native promises with deferred objects. | |
* Deferreds return an object that has a <promise>, which could be resolved via | |
* the included <resolve> and <reject> calls. | |
*/ | |
if (Promise && !("deferred" in Promise)) Promise.deferred = function() { | |
var fResolve, | |
fReject, | |
P = new Promise(function(resolve, reject) { | |
fResolve = resolve; | |
fReject = reject; | |
}); | |
return { promise:P, resolve:fResolve, reject:fReject }; | |
} | |
// Create a new deferred | |
var def = Promise.deferred(); | |
// On deferred resolution, show the result | |
def.promise.then(function (result) { | |
alert(result); | |
}); | |
// Resolve delayed | |
setTimeout(function() { | |
def.resolve('Success!'); | |
}, 2000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment