Skip to content

Instantly share code, notes, and snippets.

@flaki
Created June 7, 2014 15:18
Show Gist options
  • Save flaki/f7c0567b5e104c136dbd to your computer and use it in GitHub Desktop.
Save flaki/f7c0567b5e104c136dbd to your computer and use it in GitHub Desktop.
Deferred objects tooling based on the native ES6 Promise implementation
/*
* 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