codeMutex.js 551 B

123456789101112131415161718192021
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.codeMutex = void 0;
  4. /**
  5. * Executes only one instance of give code at a time. If other calls come in in
  6. * parallel, they get resolved to the result of the ongoing execution.
  7. */
  8. const codeMutex = () => {
  9. let result;
  10. return async (code) => {
  11. if (result)
  12. return result;
  13. try {
  14. return await (result = code());
  15. }
  16. finally {
  17. result = undefined;
  18. }
  19. };
  20. };
  21. exports.codeMutex = codeMutex;