Skip to content

Commit 9212844

Browse files
Add some clarification of what wrap does and why it is needed (#43)
Co-authored-by: Justin Ridgewell <[email protected]>
1 parent 0ca6ca1 commit 9212844

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

README.md

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -180,9 +180,10 @@ class AsyncContext<T> {
180180

181181
`AsyncContext.prototype.run()` and `AsyncContext.prototype.get()` sets and gets the current
182182
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
184184
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.
186187

187188
```typescript
188189
const context = new AsyncContext();
@@ -243,6 +244,28 @@ function randomTimeout() {
243244
}
244245
```
245246

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+
246269
> Note: There are controversial thought on the dynamic scoping and `AsyncContext`,
247270
> checkout [SCOPING.md][] for more details.
248271

0 commit comments

Comments
 (0)