mutex.js 925 B

123456789101112131415161718192021222324252627
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.mutex = void 0;
  4. const codeMutex_1 = require("./codeMutex");
  5. /**
  6. * Executes only one instance of give code at a time. For parallel calls, it
  7. * returns the result of the ongoing execution.
  8. */
  9. function mutex(fn, context) {
  10. const isDecorator = !!context;
  11. if (!isDecorator) {
  12. const mut = (0, codeMutex_1.codeMutex)();
  13. return async function (...args) {
  14. return await mut(async () => await fn.call(this, ...args));
  15. };
  16. }
  17. const instances = new WeakMap();
  18. return async function (...args) {
  19. let map = instances.get(this);
  20. if (!map)
  21. instances.set(this, (map = new WeakMap()));
  22. if (!map.has(fn))
  23. map.set(fn, (0, codeMutex_1.codeMutex)());
  24. return await map.get(fn)(async () => await fn.call(this, ...args));
  25. };
  26. }
  27. exports.mutex = mutex;