mutex.js 1.2 KB

1234567891011121314151617181920212223242526272829303132
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.mutex = void 0;
  4. const tslib_1 = require("tslib");
  5. const codeMutex_1 = require("./codeMutex");
  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 function (...args) {
  15. return tslib_1.__awaiter(this, void 0, void 0, function* () {
  16. return yield mut(() => tslib_1.__awaiter(this, void 0, void 0, function* () { return yield fn.call(this, ...args); }));
  17. });
  18. };
  19. }
  20. const instances = new WeakMap();
  21. return function (...args) {
  22. return tslib_1.__awaiter(this, void 0, void 0, function* () {
  23. let map = instances.get(this);
  24. if (!map)
  25. instances.set(this, (map = new WeakMap()));
  26. if (!map.has(fn))
  27. map.set(fn, (0, codeMutex_1.codeMutex)());
  28. return yield map.get(fn)(() => tslib_1.__awaiter(this, void 0, void 0, function* () { return yield fn.call(this, ...args); }));
  29. });
  30. };
  31. }
  32. exports.mutex = mutex;