Zone 传播

第一章介绍如何创建 Zones,并通过异步函数传播

Entering Zones, Forking and Stack Frames

首先要了解的是如何创建 zone(forked),如何通过系统传播,以及如何形象的理解 zones 和堆栈帧。

  1. // RootZone 环境的所以它难以与无 zone 区分。
  2. let rootZone = Zone.current;
  3. // We create a new zone by forking an existing zone.
  4. let zoneA = rootZone.fork({name: 'zoneA'});
  5. // Each zone has a name for debugging
  6. expect(rootZone.name).toEqual('<root>');
  7. expect(zoneA.name).toEqual('zoneA');
  8. // Child zone knows about its parent zone. (one way reference)
  9. expect(zoneA.parent).toBe(rootZone);
  10. function main() {
  11. // zones can be entered/exited using the `run` method only.
  12. zoneA.run(function fnOuter() {
  13. // inside the `run` method the Zone.current has been updated
  14. expect(Zone.current).toBe(zoneA);
  15. // Mental model: Each stack frame is associated with a zone
  16. expect(Error.captureStackTrace()).toEqual(outerLocation)
  17. // Zones are nested in the same way that stack frames are nested.
  18. rootZone.run(function fnInner() {
  19. // There is no reason why a nested stack frame must be
  20. // a child of parent stack frame zone.
  21. // This is how one can "escape" a zone.
  22. expect(Zone.current).toBe(rootZone);
  23. expect(Error.captureStackTrace()).toEqual(innerLocation)
  24. });
  25. });
  26. }
  27. main();

关键点:

  • Assigning to Zone.current is a runtime error. The only way to change Zone.current is through Zone.prototype.run().
  • A given stack frame has exactly one zone associated with it. The stack frame above or below must have the same zone, unless that stack frame is Zone.prototype.run().
  • Child zone has a reference to parent zone (but parent does not have reference to child) having parent relationship only allows the zones to be garbage collected by simply releasing a reference to a zone.

Stack Frames

It is important to understand that a given stack frame can only be associated with one zone. (i.e. it is not possible for first half of a function to run in a different zone than later half of the function. It is possible that the same function will have different zone on different invocations). Zone can only be entered or left by entering or exiting Zone.prototype.run(). Zones updates stack traces to show zones for better visibility. Below are two stack snapshots from the above example which show the associated zone for each stack frame.

重要的是要理解,给定的堆栈帧只能与一个区域相关联。 (即,函数的前半部分不可能在与函数的后半部分不同的区域中运行。相同的函数可能在不同的调用上具有不同的区域)。 只能通过输入或退出Zone.prototype.run()来输入或留下区域。 区域更新堆栈跟踪以显示区域,以提高可见性。 下面是来自上面示例的两个堆栈快照,其示出了每个堆栈帧的关联区域。

  1. outerLocation:
  2. at fnOuter()[ZoneA];
  3. at Zone.prototype.run()[<root> -> zoneA]
  4. at main()[<root>]
  5. at <anonymous>()[<root>]
  1. innerLocation:
  2. at fnInner()[<root>];
  3. at Zone.prototype.run()[zoneA -> <root>]
  4. at fnOuter()[zoneA];
  5. at Zone.prototype.run()[<root> -> zoneA]
  6. at main()[<root>]
  7. at <anonymous>()[<root>]