UNPKG

2.02 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 *
15 * @example
16 * ```js
17 * const state = await waitFor(someService, state => {
18 * return state.hasTag('loaded');
19 * });
20 *
21 * state.hasTag('loaded'); // true
22 * ```
23 *
24 * @param actorRef The actor ref to subscribe to
25 * @param predicate Determines if a value matches the condition to wait for
26 * @param options
27 * @returns A promise that eventually resolves to the emitted value
28 * that matches the condition
29 */
30
31function waitFor(actorRef, predicate, options) {
32 var resolvedOptions = _tslib.__assign(_tslib.__assign({}, defaultWaitForOptions), options);
33
34 return new Promise(function (res, rej) {
35 var done = false;
36
37 if (process.env.NODE_ENV !== 'production' && resolvedOptions.timeout < 0) {
38 console.error('`timeout` passed to `waitFor` is negative and it will reject its internal promise immediately.');
39 }
40
41 var handle = resolvedOptions.timeout === Infinity ? undefined : setTimeout(function () {
42 sub.unsubscribe();
43 rej(new Error("Timeout of ".concat(resolvedOptions.timeout, " ms exceeded")));
44 }, resolvedOptions.timeout);
45
46 var dispose = function () {
47 clearTimeout(handle);
48 done = true;
49 sub === null || sub === void 0 ? void 0 : sub.unsubscribe();
50 };
51
52 var sub = actorRef.subscribe({
53 next: function (emitted) {
54 if (predicate(emitted)) {
55 dispose();
56 res(emitted);
57 }
58 },
59 error: function (err) {
60 dispose();
61 rej(err);
62 },
63 complete: function () {
64 dispose();
65 rej(new Error("Actor terminated without satisfying predicate"));
66 }
67 });
68
69 if (done) {
70 sub.unsubscribe();
71 }
72 });
73}
74
75exports.waitFor = waitFor;