lock-controller.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. /*!
  2. * (C) Ionic http://ionicframework.com - MIT License
  3. */
  4. /**
  5. * Creates a lock controller.
  6. *
  7. * Claiming a lock means that nothing else can acquire the lock until it is released.
  8. * This can momentarily prevent execution of code that needs to wait for the earlier code to finish.
  9. * For example, this can be used to prevent multiple transitions from occurring at the same time.
  10. */
  11. const createLockController = () => {
  12. let waitPromise;
  13. /**
  14. * When lock() is called, the lock is claimed.
  15. * Once a lock has been claimed, it cannot be claimed again until it is released.
  16. * When this function gets resolved, the lock is released, allowing it to be claimed again.
  17. *
  18. * @example ```tsx
  19. * const unlock = await this.lockController.lock();
  20. * // do other stuff
  21. * unlock();
  22. * ```
  23. */
  24. const lock = async () => {
  25. const p = waitPromise;
  26. let resolve;
  27. waitPromise = new Promise((r) => (resolve = r));
  28. if (p !== undefined) {
  29. await p;
  30. }
  31. return resolve;
  32. };
  33. return {
  34. lock,
  35. };
  36. };
  37. export { createLockController as c };