UNPKG

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