Skip to content

Instantly share code, notes, and snippets.

@cdhowie
Last active October 16, 2016 23:01
Show Gist options
  • Save cdhowie/69ceb92f328db20b5b7ec59a6e5c1949 to your computer and use it in GitHub Desktop.
Save cdhowie/69ceb92f328db20b5b7ec59a6e5c1949 to your computer and use it in GitHub Desktop.
ES5-compatible defer shim

ES5-compatible polyfill for Promise.defer() that will work regardless of whether the Promise constructor invokes the passed function synchronously or asynchronously.

Promise.defer = Promise.defer || function () {
'use strict';
var result;
var resolver = function (value) {
result = result || new Promise(function (r) { r(value); });
};
var rejecter = function (reason) {
result = result || new Promise(function (_, j) { j(reason); });
};
return {
resolve: function (v) { resolver(v); },
reject: function (v) { rejecter(v); },
promise: new Promise(function (r, j) {
if (result) {
r(result);
} else {
resolver = r;
rejecter = j;
}
})
};
};
Promise.defer=Promise.defer||function(){"use strict"
var n,e=function(e){n=n||new Promise(function(n){n(e)})},i=function(e){n=n||new Promise(function(n,i){i(e)})}
return{resolve:function(n){e(n)},reject:function(n){i(n)},promise:new Promise(function(o,r){n?o(n):(e=o,i=r)})}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment