MCPcopy
hub / github.com/statelyai/xstate / waitFor

Function waitFor

packages/core/src/waitFor.ts:42–129  ·  view source on GitHub ↗
(
  actorRef: TActorRef,
  predicate: (emitted: SnapshotFrom<TActorRef>) => boolean,
  options?: Partial<WaitForOptions>
)

Source from the content-addressed store, hash-verified

40 * the condition
41 */
42export function waitFor<TActorRef extends AnyActorRef>(
43 actorRef: TActorRef,
44 predicate: (emitted: SnapshotFrom<TActorRef>) => boolean,
45 options?: Partial<WaitForOptions>
46): Promise<SnapshotFrom<TActorRef>> {
47 const resolvedOptions: WaitForOptions = {
48 ...defaultWaitForOptions,
49 ...options
50 };
51 return new Promise((res, rej) => {
52 const { signal } = resolvedOptions;
53 if (signal?.aborted) {
54 // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
55 rej(signal.reason);
56 return;
57 }
58 let done = false;
59 if (isDevelopment && resolvedOptions.timeout < 0) {
60 console.error(
61 '`timeout` passed to `waitFor` is negative and it will reject its internal promise immediately.'
62 );
63 }
64 const handle =
65 resolvedOptions.timeout === Infinity
66 ? undefined
67 : setTimeout(() => {
68 dispose();
69 rej(new Error(`Timeout of ${resolvedOptions.timeout} ms exceeded`));
70 }, resolvedOptions.timeout);
71
72 const dispose = () => {
73 clearTimeout(handle);
74 done = true;
75 sub?.unsubscribe();
76 if (abortListener) {
77 signal!.removeEventListener('abort', abortListener);
78 }
79 };
80
81 function checkEmitted(emitted: SnapshotFrom<TActorRef>) {
82 if (predicate(emitted)) {
83 dispose();
84 res(emitted);
85 }
86 }
87
88 /**
89 * If the `signal` option is provided, this will be the listener for its
90 * `abort` event
91 */
92 let abortListener: () => void | undefined;
93 // eslint-disable-next-line prefer-const
94 let sub: Subscription | undefined; // avoid TDZ when disposing synchronously
95
96 // See if the current snapshot already matches the predicate
97 checkEmitted(actorRef.getSnapshot());
98 if (done) {
99 return;

Callers 10

actor.test.tsFile · 0.90
inspect.test.tsFile · 0.90
actorLogic.test.tsFile · 0.90
waitFor.test.tsFile · 0.90
useActor.test.tsxFile · 0.85
index.test.tsxFile · 0.85
useMachine.test.tsFile · 0.85

Calls 6

disposeFunction · 0.85
checkEmittedFunction · 0.85
getSnapshotMethod · 0.80
addEventListenerMethod · 0.80
subscribeMethod · 0.65
unsubscribeMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…