countDownLatch.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. var exp = module.exports;
  2. /**
  3. * Count down to zero or timeout and invoke cb finally.
  4. */
  5. var CountDownLatch = function(count, opts, cb) {
  6. this.count = count;
  7. this.cb = cb;
  8. var self = this;
  9. if (opts.timeout) {
  10. this.timerId = setTimeout(function() {
  11. self.cb(true);
  12. }, opts.timeout);
  13. }
  14. };
  15. /**
  16. * Call when a task finish to count down.
  17. *
  18. * @api public
  19. */
  20. CountDownLatch.prototype.done = function() {
  21. if(this.count <= 0) {
  22. throw new Error('illegal state.');
  23. }
  24. this.count--;
  25. if (this.count === 0) {
  26. if (this.timerId) {
  27. clearTimeout(this.timerId);
  28. }
  29. this.cb();
  30. }
  31. };
  32. /**
  33. * Create a count down latch
  34. *
  35. * @param {Integer} count
  36. * @param {Object} opts, opts.timeout indicates timeout, optional param
  37. * @param {Function} cb, cb(isTimeout)
  38. *
  39. * @api public
  40. */
  41. exp.createCountDownLatch = function(count, opts, cb) {
  42. if(!count || count <= 0) {
  43. throw new Error('count should be positive.');
  44. }
  45. if (!cb && typeof opts === 'function') {
  46. cb = opts;
  47. opts = {};
  48. }
  49. if(typeof cb !== 'function') {
  50. throw new Error('cb should be a function.');
  51. }
  52. return new CountDownLatch(count, opts, cb);
  53. };