node/test/parallel/test-als-defaultvalue.js
James M Snell a369818b1e 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
PR-URL: https://github.com/nodejs/node/pull/57766
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
2025-04-07 13:41:18 -07:00

41 lines
1.1 KiB
JavaScript

// Flags: --async-context-frame
'use strict';
require('../common');
const {
AsyncLocalStorage,
} = require('async_hooks');
const {
strictEqual,
throws,
} = require('assert');
// ============================================================================
// The defaultValue option
const als1 = new AsyncLocalStorage();
strictEqual(als1.getStore(), undefined, 'value should be undefined');
const als2 = new AsyncLocalStorage({ defaultValue: 'default' });
strictEqual(als2.getStore(), 'default', 'value should be "default"');
const als3 = new AsyncLocalStorage({ defaultValue: 42 });
strictEqual(als3.getStore(), 42, 'value should be 42');
const als4 = new AsyncLocalStorage({ defaultValue: null });
strictEqual(als4.getStore(), null, 'value should be null');
throws(() => new AsyncLocalStorage(null), {
code: 'ERR_INVALID_ARG_TYPE',
});
// ============================================================================
// The name option
const als5 = new AsyncLocalStorage({ name: 'test' });
strictEqual(als5.name, 'test');
const als6 = new AsyncLocalStorage();
strictEqual(als6.name, '');