Skip to content

Commit 4d50eb6

Browse files
authored
Merge pull request #248 from audionerd/api-docs-fromCallback-promises-and-error-handling
Actors: add Promise example to `fromCallback`
2 parents 2fdb8d9 + cea1def commit 4d50eb6

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

docs/actors.mdx

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

413+
You may choose to use `sendBack` to report caught errors to the parent actor. This is especially helpful for handling promise rejections within a callback function, which will not be caught by [`onError`](invoke.mdx#onerror).
414+
415+
Callback functions cannot be `async` functions. But it is possible to execute a Promise within a callback function.
416+
417+
```ts
418+
const machine = createMachine({
419+
initial: 'running',
420+
states: {
421+
running: {
422+
invoke: {
423+
src: fromCallback(({ sendBack }) => {
424+
// highlight-start
425+
somePromise()
426+
.then((data) => sendBack({ type: 'done', data }))
427+
.catch((error) => sendBack({ type: 'error', data: error }));
428+
// highlight-end
429+
430+
return () => {
431+
/* cleanup function */
432+
};
433+
})
434+
},
435+
// highlight-start
436+
on: {
437+
error: {
438+
actions: ({ event }) => console.error(event.data)
439+
}
440+
}
441+
// highlight-end
442+
}
443+
}
444+
});
445+
```
446+
413447
## Higher-level actor logic
414448

415449
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)