Created
February 7, 2011 12:55
-
-
Save briancavalier/814318 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
With the help of your idea, implemente a fully method promise