async.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. var name = require('fn.name');
  3. /**
  4. * Wrap callbacks to prevent double execution.
  5. *
  6. * @param {Function} fn Function that should only be called once.
  7. * @returns {Function} A async wrapped callback which prevents multiple executions.
  8. * @public
  9. */
  10. module.exports = function one(fn) {
  11. var called = 0
  12. , value;
  13. /**
  14. * The function that prevents double execution.
  15. *
  16. * @async
  17. * @public
  18. */
  19. async function onetime() {
  20. if (called) return value;
  21. called = 1;
  22. value = await fn.apply(this, arguments);
  23. fn = null;
  24. return value;
  25. }
  26. //
  27. // To make debugging more easy we want to use the name of the supplied
  28. // function. So when you look at the functions that are assigned to event
  29. // listeners you don't see a load of `onetime` functions but actually the
  30. // names of the functions that this module will call.
  31. //
  32. // NOTE: We cannot override the `name` property, as that is `readOnly`
  33. // property, so displayName will have to do.
  34. //
  35. onetime.displayName = name(fn);
  36. return onetime;
  37. };