Previous: Handling Errors

Next: Task Groups

Child Tasks

Tasks can call other tasks by yielding 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.

Example

Waiting to start
  • Parent Task: idle
  • Child Task: idle
  • Grandchild Task: idle
export default Controller.extend({
  status: "Waiting to start",

  parentTask: task(function * () {
    this.set('status', "1. Parent: one moment...");
    yield timeout(1000);
    let value = yield this.get('childTask').perform();
    this.set('status', `5. Parent: child says "${value}"`);
    yield timeout(1000);
    this.set('status', "6. Done!");
  }).restartable(),

  childTask: task(function * () {
    this.set('status', "2. Child: one moment...");
    yield timeout(1000);
    let value = yield this.get('grandchildTask').perform();
    this.set('status', `4. Child: grandchild says "${value}"`);
    yield timeout(1000);
    return "What's up";
  }),

  grandchildTask: task(function * () {
    this.set('status', "3. Grandchild: one moment...");
    yield timeout(1000);
    return "Hello";
  }),
});
<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={{perform parentTask}}>
  {{#if parentTask.isRunning}}
    Restart Parent Task
  {{else}}
    Perform Parent Task
  {{/if}}
</button>




Previous: Handling Errors

Next: Task Groups