UNPKG

1.93 kBJavaScriptView Raw
1import { __assign } from './_virtual/_tslib.js';
2
3var defaultWaitForOptions = {
4 timeout: 10000 // 10 seconds
5
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 *
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
27function waitFor(actorRef, predicate, options) {
28 var resolvedOptions = __assign(__assign({}, defaultWaitForOptions), options);
29
30 return new Promise(function (res, rej) {
31 var done = false;
32
33 if (process.env.NODE_ENV !== 'production' && resolvedOptions.timeout < 0) {
34 console.error('`timeout` passed to `waitFor` is negative and it will reject its internal promise immediately.');
35 }
36
37 var handle = resolvedOptions.timeout === Infinity ? undefined : setTimeout(function () {
38 sub.unsubscribe();
39 rej(new Error("Timeout of ".concat(resolvedOptions.timeout, " ms exceeded")));
40 }, resolvedOptions.timeout);
41
42 var dispose = function () {
43 clearTimeout(handle);
44 done = true;
45 sub === null || sub === void 0 ? void 0 : sub.unsubscribe();
46 };
47
48 var sub = actorRef.subscribe({
49 next: function (emitted) {
50 if (predicate(emitted)) {
51 dispose();
52 res(emitted);
53 }
54 },
55 error: function (err) {
56 dispose();
57 rej(err);
58 },
59 complete: function () {
60 dispose();
61 rej(new Error("Actor terminated without satisfying predicate"));
62 }
63 });
64
65 if (done) {
66 sub.unsubscribe();
67 }
68 });
69}
70
71export { waitFor };