You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
1.7 KiB

4 years ago
  1. # once
  2. Only call a function once.
  3. ## usage
  4. ```javascript
  5. var once = require('once')
  6. function load (file, cb) {
  7. cb = once(cb)
  8. loader.load('file')
  9. loader.once('load', cb)
  10. loader.once('error', cb)
  11. }
  12. ```
  13. Or add to the Function.prototype in a responsible way:
  14. ```javascript
  15. // only has to be done once
  16. require('once').proto()
  17. function load (file, cb) {
  18. cb = cb.once()
  19. loader.load('file')
  20. loader.once('load', cb)
  21. loader.once('error', cb)
  22. }
  23. ```
  24. Ironically, the prototype feature makes this module twice as
  25. complicated as necessary.
  26. To check whether you function has been called, use `fn.called`. Once the
  27. function is called for the first time the return value of the original
  28. function is saved in `fn.value` and subsequent calls will continue to
  29. return this value.
  30. ```javascript
  31. var once = require('once')
  32. function load (cb) {
  33. cb = once(cb)
  34. var stream = createStream()
  35. stream.once('data', cb)
  36. stream.once('end', function () {
  37. if (!cb.called) cb(new Error('not found'))
  38. })
  39. }
  40. ```
  41. ## `once.strict(func)`
  42. Throw an error if the function is called twice.
  43. Some functions are expected to be called only once. Using `once` for them would
  44. potentially hide logical errors.
  45. In the example below, the `greet` function has to call the callback only once:
  46. ```javascript
  47. function greet (name, cb) {
  48. // return is missing from the if statement
  49. // when no name is passed, the callback is called twice
  50. if (!name) cb('Hello anonymous')
  51. cb('Hello ' + name)
  52. }
  53. function log (msg) {
  54. console.log(msg)
  55. }
  56. // this will print 'Hello anonymous' but the logical error will be missed
  57. greet(null, once(msg))
  58. // once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time
  59. greet(null, once.strict(msg))
  60. ```