@@ -180,9 +180,10 @@ class AsyncContext<T> {
180
180
181
181
` AsyncContext.prototype.run() ` and ` AsyncContext.prototype.get() ` sets and gets the current
182
182
value of an async execution flow. ` AsyncContext.wrap() ` allows you to opaquely
183
- capture the current value of all ` AsyncContexts ` and execute the callback at a
183
+ capture the current value of all ` AsyncContext ` s and execute the callback at a
184
184
later time with as if those values were still the current values (a snapshot and
185
- restore).
185
+ restore). Note that even with ` AsyncContext.wrap() ` , you can only access the
186
+ value associated with an ` AsyncContext ` instance if you have access to that instance.
186
187
187
188
``` typescript
188
189
const context = new AsyncContext ();
@@ -243,6 +244,28 @@ function randomTimeout() {
243
244
}
244
245
```
245
246
247
+ ` AsyncContext.wrap ` is useful for implementing APIs that logically "schedule" a
248
+ callback, so the callback will be called with the context that it logically
249
+ belongs to, regardless of the context under which it actually runs:
250
+
251
+ ``` typescript
252
+ let queue = [];
253
+
254
+ export function enqueueCallback(cb : () => void ) {
255
+ // Each callback is stored with the context at which it was enqueued.
256
+ queue .push (AsyncContext .wrap (cb ));
257
+ }
258
+
259
+ runWhenIdle (() => {
260
+ // All callbacks in the queue would be run with the current context if they
261
+ // hadn't been wrapped.
262
+ for (const cb of queue ) {
263
+ cb ();
264
+ }
265
+ queue = [];
266
+ });
267
+ ```
268
+
246
269
> Note: There are controversial thought on the dynamic scoping and ` AsyncContext ` ,
247
270
> checkout [ SCOPING.md] [ ] for more details.
248
271
0 commit comments