-
Notifications
You must be signed in to change notification settings - Fork 0
Child Tasks
Charles Demers edited this page Aug 21, 2024
·
2 revisions
Tasks can call other tasks by yield
ing the result of anotherTask.perform()
. When this happens, the Parent task will wait for the Child task to complete before proceeding. If the Parent task is canceled, the Child task will automatically be canceled as well.
import { useState } from 'react';
import { useTask, timeout } from '@mirego/houston';
export default function TestComponent() {
const [status, setStatus] = useState('Waiting to start');
const [grandchildTask] = useTask(function* () {
setStatus('3. Grandchild: one moment…');
yield timeout(1000);
return 'Hello';
});
const [childTask] = useTask(function* () {
setStatus('2. Child: one moment…');
yield timeout(1000);
const value = yield grandchildTask.perform();
setStatus(`4. Child: grandchild says "${value}"`);
yield timeout(1000);
return "What's up";
});
const [parentTask] = useTask({ restartable: true }, function* () {
setStatus('1. Parent: one moment…');
yield timeout(1000);
const value = yield childTask.perform();
setStatus(`5. Parent: child says "${value}"`);
yield timeout(1000);
setStatus('6. Done!');
});
return (
<div>
<h5>{status}</h5>
<ul>
<li>Parent Task: {parentTask.state}</li>
<li>Child Task: {childTask.state}</li>
<li>Grandchild Task: {grandchildTask.state}</li>
</ul>
<button onClick={() => parentTask.perform()} type="button">
{parentTask.isRunning ? 'Restart Parent Task' : 'Perform Parent Task'}
</button>
</div>
);
}