countDownLatch.js 727 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. var exp = module.exports;
  2. /**
  3. * Count down to zero and invoke cb finally.
  4. */
  5. var CountDownLatch = function(count, cb) {
  6. this.count = count;
  7. this.cb = cb;
  8. };
  9. /**
  10. * Call when a task finish to count down.
  11. *
  12. * @api public
  13. */
  14. CountDownLatch.prototype.done = function() {
  15. if(this.count <= 0) {
  16. throw new Error('illegal state.');
  17. }
  18. this.count--;
  19. if (this.count === 0) {
  20. this.cb();
  21. }
  22. };
  23. /**
  24. * create a count down latch
  25. *
  26. * @api public
  27. */
  28. exp.createCountDownLatch = function(count, cb) {
  29. if(!count || count <= 0) {
  30. throw new Error('count should be positive.');
  31. }
  32. if(typeof cb !== 'function') {
  33. throw new Error('cb should be a function.');
  34. }
  35. return new CountDownLatch(count, cb);
  36. };