Skip to content

Commit 450a109

Browse files
committed
Actors: add Promise example to fromCallback
1 parent cbb9387 commit 450a109

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

docs/actors.mdx

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,75 @@ Callback actors are a bit different from other actors in that they do not do the
408408
- Do not emit values when used with `.subscribe()`
409409
- Can not be stopped with `.stop()`
410410

411+
Callback functions cannot be `async` functions. But it is possible to execute a Promise within a callback function. Promise rejections will not be caught by `onError`, so you may choose to use `sendBack` to report errors caught from the Promise to the parent actor.
412+
413+
```ts
414+
const machine = createMachine({
415+
initial: 'running',
416+
states: {
417+
running: {
418+
invoke: {
419+
src: fromCallback(({ sendBack }) => {
420+
// highlight-start
421+
somePromise()
422+
.then((data) => sendBack({ type: 'done', data }))
423+
.catch((error) => sendBack({ type: 'error', data: error }));
424+
// highlight-end
425+
426+
return () => {
427+
/* cleanup function */
428+
};
429+
})
430+
},
431+
// highlight-start
432+
on: {
433+
error: {
434+
actions: ({ event }) => console.error(event.data)
435+
}
436+
}
437+
// highlight-end
438+
}
439+
}
440+
});
441+
```
442+
443+
To use `async`/`await`, you may find it more expressive to wrap your code in an [asynchronous immediately invoked function expression (IIFE)](https://developer.mozilla.org/en-US/docs/Glossary/IIFE#execute_an_async_function).
444+
445+
```ts
446+
const machine = createMachine({
447+
initial: 'running',
448+
states: {
449+
running: {
450+
invoke: {
451+
src: fromCallback(({ sendBack }) => {
452+
// highlight-start
453+
(async () => {
454+
try {
455+
const data = await somePromise();
456+
sendBack({ type: 'done', data });
457+
} catch (error) {
458+
sendBack({ type: 'error', data: error });
459+
}
460+
})();
461+
// highlight-end
462+
463+
return () => {
464+
/* cleanup function */
465+
};
466+
})
467+
},
468+
// highlight-start
469+
on: {
470+
error: {
471+
actions: ({ event }) => console.error(event.data)
472+
}
473+
}
474+
// highlight-end
475+
}
476+
}
477+
});
478+
```
479+
411480
## Higher-level actor logic
412481

413482
Higher-level actor logic enhances existing actor logic with additional functionality. For example, you can create actor logic that logs or persists actor state:

0 commit comments

Comments
 (0)