Forked from briancavalier/tiny closure Promise.js
Last active
August 29, 2015 14:26
-
-
Save olebedev/4831255d4b165c03cf2d to your computer and use it in GitHub Desktop.
A closure version of my mod (https://gist.github.com/814313) to unscriptable's tiny promise (https://gist.github.com/814052/)
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
function Promise() { | |
var callbacks = [], | |
promise = { | |
resolve: resolve, | |
reject: reject, | |
then: then, | |
safe: { | |
then: function safeThen(resolve, reject) { | |
promise.then(resolve, reject); | |
} | |
} | |
}; | |
function complete(type, result) { | |
promise.then = type === 'reject' | |
? function(resolve, reject) { reject(result); } | |
: function(resolve) { resolve(result); }; | |
promise.resolve = promise.reject = function() { throw new Error("Promise already completed"); }; | |
var i = 0, cb; | |
while(cb = callbacks[i++]) { cb[type] && cb[type](result); } | |
callbacks = null; | |
} | |
function resolve(result) { | |
complete('resolve', result); | |
} | |
function reject(err) { | |
complete('reject', err); | |
} | |
function then(resolve, reject) { | |
callbacks.push({ resolve: resolve, reject: reject }); | |
} | |
return promise; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment