Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

async_hooks: avoid unneeded AsyncResource creation #34616

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions lib/async_hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const {
NumberIsSafeInteger,
ObjectDefineProperties,
ObjectIs,
ReflectApply,
Symbol,
} = primordials;
Expand Down Expand Up @@ -284,6 +285,10 @@ class AsyncLocalStorage {
}

run(store, callback, ...args) {
// Avoid creation of an AsyncResource if store is already active
if (ObjectIs(store, this.getStore())) {
return callback(...args);
}
const resource = new AsyncResource('AsyncLocalStorage');
return resource.runInAsyncScope(() => {
this.enterWith(store);
Expand Down
17 changes: 15 additions & 2 deletions test/async-hooks/test-async-local-storage-run-resource.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,21 @@ const asyncLocalStorage = new AsyncLocalStorage();

const outerResource = executionAsyncResource();

asyncLocalStorage.run(new Map(), () => {
assert.notStrictEqual(executionAsyncResource(), outerResource);
const store = new Map();
asyncLocalStorage.run(store, () => {
assert.strictEqual(asyncLocalStorage.getStore(), store);
const innerResource = executionAsyncResource();
assert.notStrictEqual(innerResource, outerResource);
asyncLocalStorage.run(store, () => {
assert.strictEqual(asyncLocalStorage.getStore(), store);
assert.strictEqual(executionAsyncResource(), innerResource);
const otherStore = new Map();
asyncLocalStorage.run(otherStore, () => {
assert.strictEqual(asyncLocalStorage.getStore(), otherStore);
assert.notStrictEqual(executionAsyncResource(), innerResource);
assert.notStrictEqual(executionAsyncResource(), outerResource);
});
});
});

assert.strictEqual(executionAsyncResource(), outerResource);