mutex.js 938 B

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