Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. 'use strict';
  2.  
  3. /**
  4. * @example
  5. *
  6. * var Q = Q(function(o, done) {
  7. *
  8. * }, max_queue_item)
  9. *
  10. * q.enqueue(o, function(r) {
  11. *
  12. * }, ctx)
  13. *
  14. *
  15. */
  16.  
  17. function Q(fn, _max_size, when_empty) {
  18. const ctx = this;
  19. const max_size = _max_size ? _max_size : Infinity;
  20. let e = null;
  21. let count = 0;
  22.  
  23. const ret = {
  24. enqueue,
  25. };
  26.  
  27. function QItem(o, fn, ctx) {
  28. return {
  29. fn,
  30. ctx,
  31. data: o,
  32. next: null,
  33. };
  34. }
  35.  
  36. function enqueue(o, fn, ctx) {
  37. if (count >= max_size) {
  38. throw new Error('queue fulled');
  39. }
  40. count++;
  41. const item = QItem(o, fn, ctx);
  42. if (e == null) {
  43. e = item;
  44. process.nextTick(next.bind(ctx, item));
  45. } else {
  46. e.next = item;
  47. e = e.next;
  48. }
  49.  
  50. return ret;
  51. }
  52.  
  53. function next(h) {
  54. if (h == null) {
  55. e = null;
  56. if (when_empty) when_empty();
  57.  
  58. return;
  59. }
  60. count--;
  61. fn(h.data, (...args) => {
  62. h.fn.apply(h.ctx || ctx, args);
  63. }).then(next.bind(ctx, h.next), next.bind(ctx, h.next));
  64. }
  65.  
  66. return ret;
  67. }
  68.  
  69. module.exports = Q;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement