callbacks.js 2.0 KB

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