ES5-compatible polyfill for Promise.defer()
that will work regardless of whether the Promise
constructor invokes the passed function synchronously or asynchronously.
Last active
October 16, 2016 23:01
-
-
Save cdhowie/69ceb92f328db20b5b7ec59a6e5c1949 to your computer and use it in GitHub Desktop.
ES5-compatible defer shim
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
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; | |
} | |
}) | |
}; | |
}; |
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
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