waitFor.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { __assign } from './_virtual/_tslib.js';
  2. var defaultWaitForOptions = {
  3. timeout: 10000 // 10 seconds
  4. };
  5. /**
  6. * Subscribes to an actor ref and waits for its emitted value to satisfy
  7. * a predicate, and then resolves with that value.
  8. * Will throw if the desired state is not reached after a timeout
  9. * (defaults to 10 seconds).
  10. *
  11. * @example
  12. * ```js
  13. * const state = await waitFor(someService, state => {
  14. * return state.hasTag('loaded');
  15. * });
  16. *
  17. * state.hasTag('loaded'); // true
  18. * ```
  19. *
  20. * @param actorRef The actor ref to subscribe to
  21. * @param predicate Determines if a value matches the condition to wait for
  22. * @param options
  23. * @returns A promise that eventually resolves to the emitted value
  24. * that matches the condition
  25. */
  26. function waitFor(actorRef, predicate, options) {
  27. var resolvedOptions = __assign(__assign({}, defaultWaitForOptions), options);
  28. return new Promise(function (res, rej) {
  29. var done = false;
  30. if (process.env.NODE_ENV !== 'production' && resolvedOptions.timeout < 0) {
  31. console.error('`timeout` passed to `waitFor` is negative and it will reject its internal promise immediately.');
  32. }
  33. var handle = resolvedOptions.timeout === Infinity ? undefined : setTimeout(function () {
  34. sub.unsubscribe();
  35. rej(new Error("Timeout of ".concat(resolvedOptions.timeout, " ms exceeded")));
  36. }, resolvedOptions.timeout);
  37. var dispose = function () {
  38. clearTimeout(handle);
  39. done = true;
  40. sub === null || sub === void 0 ? void 0 : sub.unsubscribe();
  41. };
  42. var sub = actorRef.subscribe({
  43. next: function (emitted) {
  44. if (predicate(emitted)) {
  45. dispose();
  46. res(emitted);
  47. }
  48. },
  49. error: function (err) {
  50. dispose();
  51. rej(err);
  52. },
  53. complete: function () {
  54. dispose();
  55. rej(new Error("Actor terminated without satisfying predicate"));
  56. }
  57. });
  58. if (done) {
  59. sub.unsubscribe();
  60. }
  61. });
  62. }
  63. export { waitFor };