drifterz28
2/7/2011 - 12:55 PM

A closure version of my mod (https://gist.github.com/814313) to unscriptable's tiny promise (https://gist.github.com/814052/)

A closure version of my mod (https://gist.github.com/814313) to unscriptable's tiny promise (https://gist.github.com/814052/)

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;
};