Created
December 13, 2010 20:34
-
-
Save anonymous/739559 to your computer and use it in GitHub Desktop.
Use this function to unlock super-asynchronous goodness
This file contains hidden or 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
/* | |
* Creates a callback to be called after multiple functions are done | |
* Usage: | |
* var wait = Q.wait(function (params, subjects) { | |
* // arguments that were passed are in params.user, params.stream | |
* // this objects that were passed are in subjects.user, subjects.stream | |
* }, ['user', 'stream]); | |
* mysql("SELECT * FROM user WHERE user_id = 2", wait.fill('user')); | |
* mysql("SELECT * FROM stream WHERE publisher_id = 2", wait.fill('stream')); | |
* | |
* @param callback Function | |
* The callback to invoke when everything is ready. It is passed | |
* an array or object, depending on whether the "required" field was | |
* a number or array, respectively. | |
* @param required Array | |
* Pass an array of required field names here. | |
* @param defaultReturn | |
* Defaults to undefined. The value to return if callback is not yet ready. | |
* @return Object | |
* An object with the following method: fill(field). | |
* Call this method to return a callback. | |
*/ | |
Q.wait = function(callback, required, defaultReturn) { | |
if (Q.typeOf(required) !== 'array') { | |
return false; | |
} | |
var len = required.length; | |
var result = { | |
callback: callback, | |
params: {}, | |
subjects: {}, | |
fill: function(field) { | |
var t = this; | |
return function() { | |
t.params[field] = Array.prototype.slice.call(arguments); | |
t.subjects[field] = this; | |
t.check(); | |
}; | |
}, | |
check: function () { | |
var i, k, found; | |
for (i=0; i<len; ++i) { | |
found=false; | |
for (k in this.params) { | |
if (k === required[i]) { | |
found=true; | |
break; | |
} | |
} | |
if (!found) { | |
return defaultReturn; | |
} | |
} | |
return this.callback.call(this, this.params, this.subjects); | |
} | |
}; | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment