For AI agents: the complete documentation index is available at /tc39-atlas/llms.txt, the full documentation bundle is available at /tc39-atlas/llms-full.txt, and this page is available as Markdown at /tc39-atlas/proposals/year/pending/proposal-async-context.md.
  • 简体中文
  • Async Context S2

    中文标题:JavaScript 的异步上下文

    提案概览
    提案速览

    该提案引入了 AsyncContext.Variable 和 AsyncContext.Snapshot,用于在异步代码(例如 promise 续体、异步回调和平台任务)中隐式传播值。Variable 存储与当前执行流关联的值,而 Snapshot 捕获所有变量的当前值,并在稍后运行函数时恢复这些值。该提案还描述了内置调度器基于注册时快照恢复这些值的约定。

    Note

    以下 README 来自上游仓库,其中的阶段或状态标注可能滞后;当前信息以提案概览为准。

    JavaScript 的异步上下文

    状态:

    • TC39:Stage 2
    • WHATWG:Stage 1

    负责人:

    与小组讨论,并通过 #tc39-async-context Matrix 房间(Matrix Guide)参加每两周一次的会议。

    目录

    简介

    本提案引入了一些 API,用于在异步代码(例如 promise 续体或异步回调)中隐式传播值。

    与其他语言中的类似 API 相比,本提案将以下特性确定为非目标:

    1. 异步任务调度与拦截。
    2. 跨异步堆栈的错误处理与冒泡。

    动机

    当编写同步 JavaScript 代码时,开发者一个合理预期是值在同步执行的生命周期内始终可用。这些值可以显式传递(即作为函数或某个嵌套函数的参数,或作为闭包变量),也可以隐式传递(从调用栈中提取,例如作为函数或嵌套函数可访问的外部对象,位于作用域之外)。

    function program() {
      const value = { key: 123 };
    
      // Explicitly pass the value to function via parameters.
      // The value is available for the full execution of the function.
      explicit(value);
    
      // Explicitly captured by the closure.
      // The value is available for as long as the closure exists.
      const closure = () => {
        assert.equal(value.key, 123);
      };
    
      // Implicitly propagated via shared reference to an external variable.
      // The value is available as long as the shared reference is set.
      // In this case, for as long as the synchronous execution of the
      // try-finally code.
      try {
        shared = value;
        implicit();
      } finally {
        shared = undefined;
      }
    }
    
    function explicit(value) {
      assert.equal(value.key, 123);
    }
    
    let shared;
    function implicit() {
      assert.equal(shared.key, 123);
    }
    
    program();

    Async/await 语法改善了编写异步 JS 的人体工学。它允许开发者以同步代码的方式思考异步代码。事件循环执行代码的行为仍然与 promise 链中相同。然而,通过事件循环传递代码会丢失调用点的_隐式_信息,因为我们最终替换了调用栈。在 async/await 语法的情况下,由于与同步代码在视觉上相似,隐式调用点信息的丢失变得不可见——唯一的屏障指示是 await 关键字。结果,在同步 JS 中“直接可用”的代码在异步 JS 中会表现出意外行为,尽管看起来几乎完全相同。

    function program() {
      const value = { key: 123 };
    
      // Implicitly propagated via shared reference to an external variable.
      // The value is only available only for the _synchronous execution_ of
      // the try-finally code.
      try {
        shared = value;
        implicit();
      } finally {
        shared = undefined;
      }
    }
    
    let shared;
    async function implicit() {
      // The shared reference is still set to the correct value.
      assert.equal(shared.key, 123);
    
      await 1;
    
      // After awaiting, the shared reference has been reset to `undefined`.
      // We've lost access to our original value.
      assert.throws(() => {
        assert.equal(shared.key, 123);
      });
    }
    
    program();

    上述问题在 promise 回调风格的代码中已经存在,但 async/await 语法的引入加剧了它,因为它使栈替换几乎无法察觉。这个问题通常无法仅靠用户态代码解决。例如,如果函数被调用时调用栈已经被替换,那么该函数将永远没有机会捕获共享引用。

    function program() {
      const value = { key: 123 };
    
      // Implicitly propagated via shared reference to an external variable.
      // The value is only available only for the _synchronous execution_ of
      // the try-finally code.
      try {
        shared = value;
        setTimeout(implicit, 0);
      } finally {
        shared = undefined;
      }
    }
    
    let shared;
    function implicit() {
      // By the time this code is executed, the shared reference has already
      // been reset. There is no way for `implicit` to solve this because
      // because the bug is caused (accidentally) by the `program` function.
      assert.throws(() => {
        assert.equal(shared.key, 123);
      });
    }
    
    program();

    此外,async/await 语法绕过了用户态 Promises,使得像 Zone.js 这样对 Promise 进行插桩的现有工具,在不进行转译的情况下无法与之配合工作。

    本提案引入了一种通用机制,通过该机制,可以在事件循环的转换过程中捕获并使用丢失的隐式调用点信息,同时允许开发者基本上像在没有隐式信息的情况下那样编写异步代码。目标是减少目前在此类情况下对异步代码进行特殊处理所需的心智负担。

    本提案旨在降低开发者对生产应用进行插桩以调试真实用户问题的门槛,使其能够使用追踪工具收集额外的性能指标和有关代码流的信息。这是其他编程语言中广泛使用的方法,而由于许多 Web API 的异步特性,目前在 Web 上还无法实现。前端框架将使用本提案来减少并自动化将异步代码归属到特定组件所需的样板代码,这目前是难以调试问题的来源。

    用例

    提议的解决方案

    本提案由两个主要部分组成:

    • 用户与之交互的 API 接口,即 AsyncContext 对象。它将成为核心 ECMAScript 规范的一部分。
    • 跨异步 API 的传播。虽然 ECMA-262 定义了几个异步 API(Promise 和 FinalizationRegistry),但其中大多数由 Web 规范定义。这种传播应如何工作,见 ./WEB-INTEGRATION.md。

    AsyncContext

    AsyncContext 被设计为一种值存储,用于在逻辑相连的同步/异步代码执行之间传播上下文。

    namespace AsyncContext {
      class Variable<T> {
        constructor(options?: AsyncVariableOptions<T>);
        get name(): string;
        get(): T | undefined;
        run<R>(value: T, fn: (...args: any[])=> R, ...args: any[]): R;
      }
      interface AsyncVariableOptions<T> {
        name?: string;
        defaultValue?: T;
      }
    
      class Snapshot {
        constructor();
        run<R>(fn: (...args: any[]) => R, ...args: any[]): R;
        static wrap<T, R>(fn: (this: T, ...args: any[]) => R): (this: T, ...args: any[]) => R;
      }
    }
    AsyncContext.Variable

    Variable 是与当前执行流关联的值的容器。该值通过异步执行流传播,并可通过 Snapshot 快照和恢复。

    Variable.prototype.run() 和 Variable.prototype.get() 设置和获取异步执行流的当前值。

    const asyncVar = new AsyncContext.Variable();
    
    // Sets the current value to 'top', and executes the `main` function.
    asyncVar.run("top", main);
    
    async function main() {
      // AsyncContext.Variable is propagated on async/await.
      await Promise.resolve();
      console.log(asyncVar.get()); // => 'top'
    
      // AsyncContext.Variable is propagated through platform tasks.
      setTimeout(() => {
        console.log(asyncVar.get()); // => 'top'
    
        asyncVar.run("A", () => {
          console.log(asyncVar.get()); // => 'A'
    
          setTimeout(() => {
            console.log(asyncVar.get()); // => 'A'
          }, randomTimeout());
        });
      }, randomTimeout());
    
      // AsyncContext.Variable runs can be nested.
      asyncVar.run("B", () => {
        console.log(asyncVar.get()); // => 'B'
    
        setTimeout(() => {
          console.log(asyncVar.get()); // => 'B'
        }, randomTimeout());
      });
    
      // AsyncContext.Variable was restored after the previous run.
      console.log(asyncVar.get()); // => 'top'
    }
    
    function randomTimeout() {
      return Math.random() * 1000;
    }
    TIP

    关于 AsyncContext.Variable 的动态作用域已有长时间的详细讨论。更多细节请查看 SCOPING.md。

    宿主预期会使用本提案中的基础设施,不仅允许跟踪异步调用栈,还允许跟踪在事件循环上调度作业的其他方式(例如 setTimeout),以最大化这些用例的价值。我们在Web 集成文档中描述了与 Web 平台 API 所需的集成。

    有关用例的详细示例,可在用例和框架文档中找到。

    AsyncContext.Snapshot

    AsyncContext.Snapshot 是一种高级 API,它允许不透明地捕获所有 Variable 的当前值,并在稍后执行函数时,就像那些值仍然是当前值一样。

    Snapshot 对于实现逻辑上“调度”回调的 API 很有用,这样回调将使用它在逻辑上所属的上下文来调用,而不管它实际运行在什么上下文下:

    let queue = [];
    
    export function enqueueCallback(cb: () => void) {
      // Each callback is stored with the context at which it was enqueued.
      const snapshot = new AsyncContext.Snapshot();
      queue.push(() => snapshot.run(cb));
    }
    
    runWhenIdle(() => {
      // All callbacks in the queue would be run with the current context if they
      // hadn't been wrapped.
      for (const cb of queue) {
        cb();
      }
      queue = [];
    });

    大多数 Web 开发者,即使是直接使用 AsyncContext.Variable 的开发者,预计也永远不需要使用 AsyncContext.Snapshot。

    TIP

    关于为什么 AsyncContext.Snapshot 是必需的详细解释,可在 SNAPSHOT.md 中找到。

    请注意,即使使用 AsyncContext.Snapshot,只有当你能够访问某个 AsyncContext.Variable 实例时,才能访问与该实例关联的值。无法遍历快照中的条目或 AsyncContext.Variable。

    const asyncVar = new AsyncContext.Variable();
    
    let snapshot
    asyncVar.run("A", () => {
      // Captures the state of all AsyncContext.Variable's at this moment.
      snapshot = new AsyncContext.Snapshot();
    });
    
    asyncVar.run("B", () => {
      console.log(asyncVar.get()); // => 'B'
    
      // The snapshot will restore all AsyncContext.Variable to their snapshot
      // state and invoke the wrapped function. We pass a function which it will
      // invoke.
      snapshot.run(() => {
        // Despite being lexically nested inside 'B', the snapshot restored us to
        // to the snapshot 'A' state.
        console.log(asyncVar.get()); // => 'A'
      });
    });
    AsyncContext.Snapshot.wrap

    AsyncContext.Snapshot.wrap 是一个辅助函数,它捕获所有 Variable 的当前值并返回一个包装函数。调用该包装函数时,它会恢复所有 Variable 的状态并执行内部函数。

    const asyncVar = new AsyncContext.Variable();
    
    function fn() {
      return asyncVar.get();
    }
    
    let wrappedFn;
    asyncVar.run("A", () => {
      // Captures the state of all AsyncContext.Variable's at this moment, returning
      // wrapped closure that restores that state.
      wrappedFn = AsyncContext.Snapshot.wrap(fn)
    });
    
    
    console.log(fn()); // => undefined
    console.log(wrappedFn()); // => 'A'

    你可以把它看作 Snapshot 的一个更方便的版本,其中只需要包装单个函数。它也为不支持 AsyncContext 的库的使用者提供了一种便捷方式,以确保该函数在正确的执行上下文中执行。

    // User code that uses a legacy library
    const asyncVar = new AsyncContext.Variable();
    
    function fn() {
        return asyncVar.get();
    }
    
    asyncVar.run("A", () => {
        defer(fn); // setTimeout schedules during "A" context.
    })
    asyncVar.run("B", () => {
        defer(fn); // setTimeout is not called, fn will still see "A" context.
    })
    asyncVar.run("C", () => {
        const wrapped = AsyncContext.Snapshot.wrap(fn);
        defer(wrapped); // wrapped callback captures "C" context.
    })
    
    
    // Some legacy library that queues multiple callbacks per macrotick
    // Because the setTimeout is called a single time per queue batch,
    // all callbacks will be invoked with _that_ context regardless of
    // whatever context is active during the call to `defer`.
    const queue = [];
    function defer(callback) {
        if (queue.length === 0) setTimeout(processQueue, 1);
        queue.push(callback);
    }
    function processQueue() {
        for (const cb of queue) {
            cb();
        }
        queue.length = 0;
    }

    示例

    确定任务的发起者

    像 OpenTelemetry 这样的应用监控工具将其追踪 span 保存在 AsyncContext.Variable 中,并在需要确定是什么启动了这条交互链时检索该 span。

    这些库无法侵入开发者 API 来实现无缝监控。追踪 span 不需要由用户代码手动传递。

    // tracer.js
    
    const asyncVar = new AsyncContext.Variable();
    export function run(cb) {
      // (a)
      const span = {
        startTime: Date.now(),
        traceId: randomUUID(),
        spanId: randomUUID(),
      };
      asyncVar.run(span, cb);
    }
    
    export function end() {
      // (b)
      const span = asyncVar.get();
      span?.endTime = Date.now();
    }
    // my-app.js
    import * as tracer from "./tracer.js";
    
    button.onclick = (e) => {
      // (1)
      tracer.run(() => {
        fetch("https://example.com").then((res) => {
          // (2)
    
          return processBody(res.body).then((data) => {
            // (3)
    
            const dialog = html`<dialog>
              Here's some cool data: ${data} <button>OK, cool</button>
            </dialog>`;
            dialog.show();
    
            tracer.end();
          });
        });
      });
    };

    在上面的示例中,run 和 end 不与实际代码函数共享相同的词法作用域,并且它们能够进行异步重入,因此能够并发地进行多重跟踪。

    传递性任务归属

    用户任务可以带有归属信息进行调度。使用 AsyncContext.Variable,任务归属会在异步任务流中传播,子任务可以使用相同的优先级进行调度。

    const scheduler = {
      asyncVar: new AsyncContext.Variable(),
      postTask(task, options) {
        // In practice, the task execution may be deferred.
        // Here we simply run the task immediately.
        return this.asyncVar.run({ priority: options.priority }, task);
      },
      currentTask() {
        return this.asyncVar.get() ?? { priority: "default" };
      },
    };
    
    const res = await scheduler.postTask(task, { priority: "background" });
    console.log(res);
    
    async function task() {
      // Fetch remains background priority by referring to scheduler.currentTask().
      const resp = await fetch("/hello");
      const text = await resp.text();
    
      scheduler.currentTask(); // => { priority: 'background' }
      return doStuffs(text);
    }
    
    async function doStuffs(text) {
      // Some async calculation...
      return text;
    }

    用户态队列

    用户态队列可以使用 AsyncContext.Snapshot 实现,以传播所有 AsyncContext.Variable 的值,而无需访问其中任何一个。这使得用户态队列的实现可以与 AsyncContext.Variable 的使用者解耦。

    // The scheduler doesn't access to any AsyncContext.Variable.
    const scheduler = {
      queue: [],
      postTask(task) {
        // Each callback is stored with the context at which it was enqueued.
        const snapshot = new AsyncContext.Snapshot();
        queue.push(() => snapshot.run(task));
      },
      runWhenIdle() {
        // All callbacks in the queue would be run with the current context if they
        // hadn't been wrapped.
        for (const cb of this.queue) {
          cb();
        }
        this.queue = [];
      }
    };
    
    function userAction() {
      scheduler.postTask(function userTask() {
        console.log(traceContext.get());
      });
    }
    
    // Tracing libraries can use AsyncContext.Variable to store tracing contexts.
    const traceContext = new AsyncContext.Variable();
    traceContext.run("trace-id-a", userAction);
    traceContext.run("trace-id-b", userAction);
    
    scheduler.runWhenIdle();
    // The userTask will be run with the trace context it was enqueued with.
    // => 'trace-id-a'
    // => 'trace-id-b'

    常见问题

    是否有先例?

    更多细节请查看 prior-arts.md。

    为什么 run 要接收一个函数?

    Variable.prototype.run 和 Snapshot.prototype.run 方法接收一个要执行的函数,因为它确保异步上下文变量在给定执行流中始终包含一致的值。任何修改都必须在异步执行流的子图中进行,并且不能影响其父级或兄弟作用域。

    const asyncVar = new AsyncContext.Variable();
    asyncVar.run("A", async () => {
      asyncVar.get(); // => 'A'
    
      // ...arbitrary synchronous codes.
      // ...or await-ed asynchronous calls.
    
      // The value can not be modified at this point.
      asyncVar.get(); // => 'A'
    });

    这提高了异步上下文变量的完整性,并使它们更容易推断异步变量的值来自何处。

    AsyncContext 如何与内置调度器交互?

    每当调度器(例如 setTimeout、addEventListener 或 Promise.prototype.then)运行用户提供的回调时,它必须选择在哪个快照中运行该回调。虽然用户态调度器可以在这里自由做出任何选择,但本提案采用一种约定:内置调度器将始终在回调被传递给内置函数时(即“注册时”)处于活动状态的快照中运行回调。这等同于用户在传递所有回调之前显式调用 AsyncContext.Snapshot.wrap 所发生的情况。

    这一选择与 run 接收函数所产生的函数作用域结构最为一致,也是在可能替代方案中定义最明确的选项。例如,许多事件监听器可能以编程方式或通过用户交互发起;在前一种情况下,可能存在更新的相关快照,但不同事件类型甚至同一事件类型的不同实例之间并不一致。另一方面,将回调传递给内置函数发生在定义非常明确的时间。

    注册时快照的另一个优点是,预期可以减少退出默认快照所需的干预量。因为 AsyncContext 是一个微妙的特性,期望每个 Web 开发者都完整理解其细微差别是不合理的。此外,重要的是库使用者不应需要知道库实现隐式传递的变量的性质。如果出现开发者认为需要在将回调传递到任何地方之前包装回调的常见做法,那将是有害的。让函数在不同快照中运行的主要手段是调用 Snapshot.wrap,但当将回调传递给内置函数时,这将是幂等的,从而既降低了这种常见做法一开始出现的可能性,也降低了在无必要情况下发生时的危害。

    如果我需要访问来自更新原因的更快照怎么办?

    注册时快照的缺点是,无法选择_退出_快照恢复,以访问快照在被恢复_之前_本应是什么。这种快照更相关的用例包括

    • 以编程方式派发的事件,其处理程序在应用程序初始化时安装
    • 未处理的拒绝处理程序是上述情况的一个具体示例
    • 跟踪执行流,其中一个任务“跟随”自兄弟任务

    如上所述,替代快照选择要具体得多,更针对单个用例,但它们可以通过侧信道提供。例如,Web 规范可以规定某些事件类型将在事件对象上暴露一个 originSnapshot 属性(实际名称待定),其中包含来自发起该事件的特定时间点的活动 AsyncContext.Snapshot。

    通过侧信道提供这些额外快照,比默认切换到它们,或通过通用的“前一个快照”机制,有几个好处:

    • 不同类型的调度器可能有各种潜在的发起点,其作用域可以通过明确定义的侧信道精确匹配
    • 通过已知侧信道访问避免了回调被多次包装时幂等性的丧失(而“前一个快照”会变得不清晰得多)
    • 没有单一的包装方法供开发者养成坏习惯