Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * 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;
- };
Add Comment
Please, Sign In to add comment