From 69a25e2b5f9d773c73e2806f6b875df73e9c1188 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sat, 5 Apr 2025 13:28:51 -0700 Subject: [PATCH 1/2] lib: add defaultValue and name options to AsyncLocalStorage The upcoming `AsyncContext` specification adds a default value and name to async storage variables. This adds the same to `AsyncLocalStorage` to promote closer alignment with the pending spec. ```js const als = new AsyncLocalStorage({ name: 'foo', defaultValue: 123, }); console.log(als.name); // 'foo' console.log(als.getStore()); // 123 ``` Refs: https://github.com/tc39/proposal-async-context/blob/master/spec.html --- doc/api/async_context.md | 19 ++++++++- .../async_context_frame.js | 33 ++++++++++++++- .../async_local_storage/async_hooks.js | 30 +++++++++++++- .../test-als-defaultvalue-original.js | 40 +++++++++++++++++++ test/parallel/test-als-defaultvalue.js | 40 +++++++++++++++++++ 5 files changed, 159 insertions(+), 3 deletions(-) create mode 100644 test/parallel/test-als-defaultvalue-original.js create mode 100644 test/parallel/test-als-defaultvalue.js diff --git a/doc/api/async_context.md b/doc/api/async_context.md index c7aaac3dbc438f..e8c58eae962ebf 100644 --- a/doc/api/async_context.md +++ b/doc/api/async_context.md @@ -116,13 +116,16 @@ Each instance of `AsyncLocalStorage` maintains an independent storage context. Multiple instances can safely exist simultaneously without risk of interfering with each other's data. -### `new AsyncLocalStorage()` +### `new AsyncLocalStorage([options])` +* `options` {Object} + * `defaultValue` {any} The default value to be used when no store is provided. + * `name` {string} A name for the `AsyncLocalStorage` value. + Creates a new instance of `AsyncLocalStorage`. Store is only provided within a `run()` call or after an `enterWith()` call. @@ -286,6 +293,16 @@ emitter.emit('my-event'); asyncLocalStorage.getStore(); // Returns the same object ``` +### `asyncLocalStorage.name` + + + +* {string} + +The name of the `AsyncLocalStorage` instance if provided. + ### `asyncLocalStorage.run(store, callback[, ...args])`