callbacks.cjs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. "use strict";
  2. /* eslint-disable @typescript-eslint/no-explicit-any */
  3. var __importDefault = (this && this.__importDefault) || function (mod) {
  4. return (mod && mod.__esModule) ? mod : { "default": mod };
  5. };
  6. Object.defineProperty(exports, "__esModule", { value: true });
  7. exports.awaitAllCallbacks = exports.consumeCallback = exports.getQueue = void 0;
  8. const p_queue_1 = __importDefault(require("p-queue"));
  9. const globals_js_1 = require("./async_local_storage/globals.cjs");
  10. let queue;
  11. /**
  12. * Creates a queue using the p-queue library. The queue is configured to
  13. * auto-start and has a concurrency of 1, meaning it will process tasks
  14. * one at a time.
  15. */
  16. function createQueue() {
  17. const PQueue = "default" in p_queue_1.default ? p_queue_1.default.default : p_queue_1.default;
  18. return new PQueue({
  19. autoStart: true,
  20. concurrency: 1,
  21. });
  22. }
  23. function getQueue() {
  24. if (typeof queue === "undefined") {
  25. queue = createQueue();
  26. }
  27. return queue;
  28. }
  29. exports.getQueue = getQueue;
  30. /**
  31. * Consume a promise, either adding it to the queue or waiting for it to resolve
  32. * @param promiseFn Promise to consume
  33. * @param wait Whether to wait for the promise to resolve or resolve immediately
  34. */
  35. async function consumeCallback(promiseFn, wait) {
  36. if (wait === true) {
  37. // Clear config since callbacks are not part of the root run
  38. // Avoid using global singleton due to circuluar dependency issues
  39. const asyncLocalStorageInstance = (0, globals_js_1.getGlobalAsyncLocalStorageInstance)();
  40. if (asyncLocalStorageInstance !== undefined) {
  41. await asyncLocalStorageInstance.run(undefined, async () => promiseFn());
  42. }
  43. else {
  44. await promiseFn();
  45. }
  46. }
  47. else {
  48. queue = getQueue();
  49. void queue.add(async () => {
  50. const asyncLocalStorageInstance = (0, globals_js_1.getGlobalAsyncLocalStorageInstance)();
  51. if (asyncLocalStorageInstance !== undefined) {
  52. await asyncLocalStorageInstance.run(undefined, async () => promiseFn());
  53. }
  54. else {
  55. await promiseFn();
  56. }
  57. });
  58. }
  59. }
  60. exports.consumeCallback = consumeCallback;
  61. /**
  62. * Waits for all promises in the queue to resolve. If the queue is
  63. * undefined, it immediately resolves a promise.
  64. */
  65. function awaitAllCallbacks() {
  66. return typeof queue !== "undefined" ? queue.onIdle() : Promise.resolve();
  67. }
  68. exports.awaitAllCallbacks = awaitAllCallbacks;