Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
async_hooks: enable AsyncLocalStorage once constructed
This fixes the leak behavior when using `enterWith` when no
`AsyncLocalStorage`s were enabled inside a promise.
  • Loading branch information
legendecas committed Apr 25, 2025
commit 0ee37f3909ed9564a97506a633090374141dc8e5
2 changes: 2 additions & 0 deletions lib/internal/async_local_storage/async_hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ class AsyncLocalStorage {
if (options.name !== undefined) {
this.#name = `${options.name}`;
}

this._enable();
}

/** @type {string} */
Expand Down
37 changes: 37 additions & 0 deletions test/parallel/test-async-local-storage-enter-with.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const { AsyncLocalStorage } = require('async_hooks');

// Verify that `enterWith()` does not leak the store to the parent context in a promise.

const als = new AsyncLocalStorage();

async function asyncFunctionAfterAwait() {
await 0;
als.enterWith('after await');
}

function promiseThen() {
return Promise.resolve()
.then(() => {
als.enterWith('inside then');
});
}

async function asyncFunctionBeforeAwait() {
als.enterWith('before await');
await 0;
}

async function main() {
await asyncFunctionAfterAwait();
await promiseThen();
assert.strictEqual(als.getStore(), undefined);

// This is a known limitation of the `enterWith` API.
await asyncFunctionBeforeAwait();
assert.strictEqual(als.getStore(), 'before await');
}

main().then(common.mustCall());