1

I want to do some asynchronous work by using zone.js. Mostly it will be zone.js microTask. When I got the desired output, I wish to cancel all the running and scheduled tasks. I am a bit confused about where to cancel the tasks.

Here my code is,

class ZoneSpec {
  constructor(name) {
    this.name = name;
    this.properties = {};
    this._zoneTasks = [];
  }

  onHandleError(parentZoneDelegate, currentZone, targetZone, error) {
    console.log(error);
  }

  onInvokeTask(parentZoneDelegate, currentZone, targetZone, task, ...args) {
    return parentZoneDelegate.invokeTask(targetZone, task, ...args);
  }

  onScheduleTask(parentZoneDelegate, currentZone, targetZone, task) {
    this._zoneTasks.push(task);
    return parentZoneDelegate.scheduleTask(targetZone, task);
  }

  cleanup() {
    while (this._zoneTasks.length) {
      let task;
      try {
        task = this._zoneTasks.pop();
        if (task.state != `notScheduled`) Zone.current.cancelTask(task);
      } catch (e) {
        console.error("error::" + e.message);
      }
    }
  }
}

const spec = new ZoneSpec("async-task");

const asyncZone = Zone.current.fork(spec);

const macroTask = () => {
  setInterval(() => {
    console.log("async task");
  }, 1000);
};

const microTask = () => {
  Promise.resolve(0).then(() => {
    macroTask();
  });
};

asyncZone.run(microTask);

setTimeout(() => {
  Zone.current.runGuarded(() => {
    spec.cleanup();
  });
}, 5000);

The error I am getting is,

async task
async task
async task
async task
macroTask
error::A task can only be cancelled in the zone of creation! (Creation: async-task; Execution: <root>)
microTask
async task
async task

Please someone put light for this problem. Many thanks...!

Gokulakannan T
  • 586
  • 4
  • 14
  • Could you post a full example? – jiali passion Mar 01 '20 at 13:21
  • @jialipassion, Actually it is not yet implemented with anything. Before the start, I did the analysis on zone.js. I have uploaded it in my [repository](https://bitbucket.org/GokulakannanT/zonejs-workout/src/master/). To see the output, just do `node index.js`, we can see the error logs in terminal console – Gokulakannan T Mar 02 '20 at 14:19

0 Answers0