File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change @@ -147,6 +147,48 @@ this time will print the stack trace and exit. See
147
147
Creating an async resource within the ` onPropagate ` callback will result in
148
148
a recursive call to ` onPropagate ` .
149
149
150
+ ### ` asyncLocalStorage.bind(fn, thisArg) `
151
+
152
+ <!-- YAML
153
+ added: REPLACEME
154
+ -->
155
+
156
+ * ` fn ` {Function} The function to bind to the current execution context.
157
+ * ` thisArg ` {any}
158
+
159
+ Binds the given function to the current execution context.
160
+
161
+ The returned function will have an ` asyncResource ` property referencing
162
+ the ` AsyncResource ` to which the function is bound.
163
+
164
+ ### ` asyncLocalStorage.snapshot() `
165
+
166
+ <!-- YAML
167
+ added: REPLACEME
168
+ -->
169
+
170
+ Returns a callback that captures the current async context and invokes a callback passed into it within the captured async context.
171
+
172
+ ``` js
173
+ const asyncLocalStorage = new AsyncLocalStorage ();
174
+ const runInAsyncScope = asyncLocalStorage .run (123 , () => als .snapshot ());
175
+ const result = asyncLocalStorage .run (321 , () => runInAsyncScope (() => asyncLocalStorage .getStore ()));
176
+ console .log (result) // returns 123
177
+ ```
178
+
179
+ AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple async context tracking purposes, for example:
180
+
181
+ ``` js
182
+ class Foo {
183
+ #runInAsyncScope = AsyncLocalStorage .snapshot ();
184
+
185
+ get () { return this .#runInAsyncScope (() => asyncLocalStorage .getStore ()); }
186
+ }
187
+
188
+ const foo = asyncLocalStorage .run (123 , () => new Foo ());
189
+ console .log (asyncLocalStorage .run (321 , () => foo .get ())) // returns 123
190
+ ```
191
+
150
192
### ` asyncLocalStorage.disable() `
151
193
152
194
<!-- YAML
Original file line number Diff line number Diff line change @@ -288,6 +288,14 @@ class AsyncLocalStorage {
288
288
this . _onPropagate = onPropagate ;
289
289
}
290
290
291
+ static bind ( fn , thisArg ) {
292
+ return new AsyncResource ( 'bound-anonymous-fn' ) . bind ( fn , thisArg ) ;
293
+ }
294
+
295
+ static snapshot ( ) {
296
+ return AsyncLocalStorage . bind ( ( cb , ...args ) => cb ( ...args ) ) ;
297
+ }
298
+
291
299
disable ( ) {
292
300
if ( this . enabled ) {
293
301
this . enabled = false ;
You can’t perform that action at this time.
0 commit comments