Guest User

Untitled

a guest
Jul 17th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. /*
  2. * Creates a callback to be called after multiple functions are done
  3. * Usage:
  4. * var wait = Q.wait(function (params, subjects) {
  5. * // arguments that were passed are in params.user, params.stream
  6. * // this objects that were passed are in subjects.user, subjects.stream
  7. * }, ['user', 'stream]);
  8. * mysql("SELECT * FROM user WHERE user_id = 2", wait.fill('user'));
  9. * mysql("SELECT * FROM stream WHERE publisher_id = 2", wait.fill('stream'));
  10. *
  11. * @param callback Function
  12. * The callback to invoke when everything is ready. It is passed
  13. * an array or object, depending on whether the "required" field was
  14. * a number or array, respectively.
  15. * @param required Array
  16. * Pass an array of required field names here.
  17. * @param defaultReturn
  18. * Defaults to undefined. The value to return if callback is not yet ready.
  19. * @return Object
  20. * An object with the following method: fill(field).
  21. * Call this method to return a callback.
  22. */
  23. Q.wait = function(callback, required, defaultReturn) {
  24. if (Q.typeOf(required) !== 'array') {
  25. return false;
  26. }
  27. var len = required.length;
  28. var result = {
  29. callback: callback,
  30. params: {},
  31. subjects: {},
  32. fill: function(field) {
  33. var t = this;
  34. return function() {
  35. t.params[field] = Array.prototype.slice.call(arguments);
  36. t.subjects[field] = this;
  37. t.check();
  38. };
  39. },
  40. check: function () {
  41. var i, k, found;
  42. for (i=0; i<len; ++i) {
  43. found=false;
  44. for (k in this.params) {
  45. if (k === required[i]) {
  46. found=true;
  47. break;
  48. }
  49. }
  50. if (!found) {
  51. return defaultReturn;
  52. }
  53. }
  54. return this.callback.call(this, this.params, this.subjects);
  55. }
  56. };
  57. return result;
  58. };
Add Comment
Please, Sign In to add comment