其他 -  任务

优质
小牛编辑
130浏览
2023-12-01

A task is special because knowing when a task is about to exit is useful in these circumstances:

  • Frameworks know when to render the UI.
  • Measuring enter/leave allows knowing total script/task time.
  • Exiting returning execution to native code allows rendering or doing I/O operations. (Knowing when it is about to happen allows for transactional behavior, ie doing things before rendering and or I/O.)
  • Test frameworks can enforce sync tests by throwing on task creation.
  • Long stack traces across async boundaries, by tracking task scheduling.
  • Tracking user perceived actions by tracking when async tasks triggered by user complete.

There are three kinds of tasks of interest:

  1. MicroTask: A microtask is work which will execute as soon as possible on empty stack frame. A microtask is guaranteed to run before host environment performs rendering or I/O operations. A microtask queue must be empty before another MacroTask or EventTask runs. (i.e. Promise.then() executes in microtask)
  2. MacroTask: Macro tasks are interleaved with rendering and I/O operations of the host environment. (ie setTimeout, setInterval, etc..) Macro tasks are guaranteed to run at least once or canceled (some can run repeatedly such as setInterval). Macro tasks have an implied execution order.
  • Knowing when a task has executed and a microtask queue is empty allows frameworks to know when it is time to render the UI.
  • Enforcing that no tasks are scheduled allows test frameworks to ensure that the test is synchronous (and hence fast and non-flaky).
  • Tracking when all scheduled tasks are executed allows a test framework to know when an asynchronous test has completed.
  • Tracking tasks which originated from a user action and waiting until all scheduled tasks are executed allows application to track perceived user latency of that action.

Another way to think about the need for tasks is that without task the above behaviors are not possible to implement.