@@ -134,6 +134,56 @@ changes: |
134 | 134 | Creates a new instance of `AsyncLocalStorage`. Store is only provided within a |
135 | 135 | `run()` call or after an `enterWith()` call. |
136 | 136 |
|
| 137 | +### Static method: `AsyncLocalStorage.bind(fn)` |
| 138 | + |
| 139 | +<!-- YAML |
| 140 | +added: REPLACEME |
| 141 | +--> |
| 142 | + |
| 143 | +> Stability: 1 - Experimental |
| 144 | +
|
| 145 | +* `fn` {Function} The function to bind to the current execution context. |
| 146 | +* Returns: {Function} A new function that calls `fn` within the captured |
| 147 | + execution context. |
| 148 | + |
| 149 | +Binds the given function to the current execution context. |
| 150 | + |
| 151 | +### Static method: `AsyncLocalStorage.snapshot()` |
| 152 | + |
| 153 | +<!-- YAML |
| 154 | +added: REPLACEME |
| 155 | +--> |
| 156 | + |
| 157 | +> Stability: 1 - Experimental |
| 158 | +
|
| 159 | +* Returns: {Function} A new function with the signature |
| 160 | + `(fn: (...args) : R, ...args) : R`. |
| 161 | + |
| 162 | +Captures the current execution context and returns a function that accepts a |
| 163 | +function as an argument. Whenever the returned function is called, it |
| 164 | +calls the function passed to it within the captured context. |
| 165 | + |
| 166 | +```js |
| 167 | +const asyncLocalStorage = new AsyncLocalStorage(); |
| 168 | +const runInAsyncScope = asyncLocalStorage.run(123, () => asyncLocalStorage.snapshot()); |
| 169 | +const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); |
| 170 | +console.log(result); // returns 123 |
| 171 | +``` |
| 172 | + |
| 173 | +AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple |
| 174 | +async context tracking purposes, for example: |
| 175 | + |
| 176 | +```js |
| 177 | +class Foo { |
| 178 | + #runInAsyncScope = AsyncLocalStorage.snapshot(); |
| 179 | + |
| 180 | + get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } |
| 181 | +} |
| 182 | + |
| 183 | +const foo = asyncLocalStorage.run(123, () => new Foo()); |
| 184 | +console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 |
| 185 | +``` |
| 186 | + |
137 | 187 | ### `asyncLocalStorage.disable()` |
138 | 188 |
|
139 | 189 | <!-- YAML |
|