receiver.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. * Expose `Receiver`.
  3. */
  4. module.exports = Receiver
  5. /**
  6. * Initialize a `Receiver`.
  7. *
  8. * @param {Mixed} val
  9. * @api private
  10. */
  11. function Receiver(val) {
  12. this.val = val
  13. this.isAdded = false
  14. this.err = null
  15. this.cb = null
  16. this.isDone = false
  17. }
  18. /**
  19. * Call the callback if the pending add is complete.
  20. *
  21. * @api private
  22. */
  23. Receiver.prototype.attemptNotify = function () {
  24. if ((this.isAdded || this.err) && this.cb && !this.isDone) {
  25. this.isDone = true
  26. setImmediate(function () { this.cb(this.err) }.bind(this))
  27. }
  28. }
  29. /**
  30. * Reject the pending add with an error.
  31. *
  32. * @param {Error} err
  33. * @api private
  34. */
  35. Receiver.prototype.error = function (err) {
  36. this.err = err
  37. this.attemptNotify()
  38. }
  39. /**
  40. * Get the `val` and set the state of the value to added
  41. *
  42. * @return {Mixed} val
  43. * @api private
  44. */
  45. Receiver.prototype.add = function () {
  46. this.isAdded = true
  47. this.attemptNotify()
  48. return this.val
  49. }
  50. /**
  51. * Register the callback.
  52. *
  53. * @api private
  54. */
  55. Receiver.prototype.callback = function (cb) {
  56. this.cb = cb
  57. this.attemptNotify()
  58. }