What does hasPendingMacrotasks and hasPendingMicrotasks do?

What is the difference between hasPendingMacrotasks or hasPendingMicrotasks in NgZone? The documentation seems to be missing information. All I know is that they return a boolean. But what exactly are they checking? What is considered a micro-task? And what is considered a macro task?

class NgZone { static isInAngularZone() : boolean static assertInAngularZone() : void static assertNotInAngularZone() : void constructor({enableLongStackTrace = false}: any) run(fn: () => any) : any runGuarded(fn: () => any) : any runOutsideAngular(fn: () => any) : any onUnstable : EventEmitter<any> onMicrotaskEmpty : EventEmitter<any> onStable : EventEmitter<any> onError : EventEmitter<any> isStable : boolean hasPendingMicrotasks : boolean hasPendingMacrotasks : boolean } 

My best guess is that micro refers to tasks from a particular class, while a macro probably refers to a task with respect to the entire application. Can anyone confirm or confirm this assumption? Or shed light on the specifics?

NgZone Docs:

https://angular.io/docs/ts/latest/api/core/index/NgZone-class.html#!#hasPendingMicrotasks-anchor

+5
source share
1 answer

There are three types of tasks

1) MicroTask :

A microtask is a job that will be executed as soon as possible on an empty stack frame. It is guaranteed that microloading will be performed before the host environment performs rendering or I / O. The microtask queue must be empty before running another macro or EventTask.

i.e. Promise.then() is executed in microtask

2) MacroTask

Macro tasks alternate with rendering and I / O in the host environment. It is guaranteed that they will be executed at least once or canceled (some of them may be repeated several times, for example, setInterval ). Macro tasks have an implied order of execution.

i.e. setTimeout , setInterval , setImmediate

3) EventTask

EventTasks are similar to macro tasks, but unlike macro tasks, they never run. When the EventTask is launched, it first frees all subsequent tasks in the macro queue. Event tasks do not create a queue.

i.e. user click , mousemove , XHR state change.

Why is it useful to know if any of the tasks are currently being performed?

  • Knowing when the task is completed and the microtask queue is empty, developers can know when it is time to render the interface.

  • Tracking the completion of all scheduled tasks allows the test structure to know when the asynchronous test completed.

ng_zone.ts

 private checkStable() { if (this._nesting == 0 && !this._hasPendingMicrotasks && !this._isStable) { try { this._nesting++; this._onMicrotaskEmpty.emit(null); } finally { this._nesting--; if (!this._hasPendingMicrotasks) { try { this.runOutsideAngular(() => this._onStable.emit(null)); } finally { this._isStable = true; } } } } } 

enter image description here

see also

+6
source

Source: https://habr.com/ru/post/1266878/


All Articles