waitFor.js 2.1 KB

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