UNPKG

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