Skip to content

Instantly share code, notes, and snippets.

@nmoinvaz
Last active August 2, 2018 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmoinvaz/86e27a56a0bebf2da94d84905aee1d2e to your computer and use it in GitHub Desktop.
Save nmoinvaz/86e27a56a0bebf2da94d84905aee1d2e to your computer and use it in GitHub Desktop.
Promise finally and defer polyfill
/**
* Promise.prototype.finally
*
* Pulled from https://github.com/domenic/promises-unwrapping/issues/18#issuecomment-57801572
* https://github.com/matthew-andrews/Promise.prototype.finally/blob/master/finally.js
* @author @stefanpenner, @matthew-andrews
*
* Promise.defer
*
* Pulled from http://bluebirdjs.com/docs/api/deferred-migration.html
* @author @cdhowie
*/
(function() {
// Get a handle on the global object
var local;
if (typeof global !== 'undefined') local = global;
else if (typeof window !== 'undefined' && window.document) local = window;
else local = self;
// It's replaced unconditionally to preserve the expected behavior
// in programs even if there's ever a native finally.
local.Promise.prototype['finally'] = local.Promise.prototype['finally'] || function (callback) {
var constructor = this.constructor;
return this.then(function(value) {
return constructor.resolve(callback()).then(function() {
return value;
});
}, function(reason) {
return constructor.resolve(callback()).then(function() {
throw reason;
});
});
};
local.Promise['defer'] = local.Promise['defer'] || function () {
var result, resolve, reject;
var self = this;
return {
resolve: function (value) {
if (resolve) {
resolve(value);
} else {
result = result || new self(function (r) { r(value); });
}
},
reject: function (reason) {
if (reject) {
reject(reason);
} else {
result = result || new self(function (_, j) { j(reason); });
}
},
promise: new self(function (r, j) {
if (result) {
r(result);
} else {
resolve = r;
reject = j;
}
})
};
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment