diff options
author | Alex Yang <himself65@outlook.com> | 2024-04-02 17:53:29 -0500 |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-04-02 22:53:29 +0000 |
commit | 8eb2b6c61f9fdac12f8bab23ad3e9ef71c7c59b1 (patch) | |
tree | 2f214f52b873d4dabd2a7e24e082206ae3c29656 | |
parent | c0b7454175afdefa0b8e73a04aadeb874eb2e766 (diff) |
feat: improve AsyncLocalStorage api (#23175)
Fixes: https://github.com/denoland/deno/issues/23174
-rw-r--r-- | ext/node/polyfills/async_hooks.ts | 11 | ||||
-rw-r--r-- | tests/unit_node/async_hooks_test.ts | 31 |
2 files changed, 42 insertions, 0 deletions
diff --git a/ext/node/polyfills/async_hooks.ts b/ext/node/polyfills/async_hooks.ts index d60334346..ea0bfb944 100644 --- a/ext/node/polyfills/async_hooks.ts +++ b/ext/node/polyfills/async_hooks.ts @@ -316,6 +316,17 @@ export class AsyncLocalStorage { ); Scope.enter(frame); } + + static bind(fn: (...args: unknown[]) => unknown) { + return AsyncResource.bind(fn); + } + + static snapshot() { + return AsyncLocalStorage.bind(( + cb: (...args: unknown[]) => unknown, + ...args: unknown[] + ) => cb(...args)); + } } export function executionAsyncId() { diff --git a/tests/unit_node/async_hooks_test.ts b/tests/unit_node/async_hooks_test.ts index 076d14b54..2ed197c2d 100644 --- a/tests/unit_node/async_hooks_test.ts +++ b/tests/unit_node/async_hooks_test.ts @@ -94,3 +94,34 @@ Deno.test(async function enterWith() { assertEquals(await deferred.promise, { x: 2 }); assertEquals(await deferred1.promise, { x: 1 }); }); + +Deno.test(async function snapshot() { + const als = new AsyncLocalStorage(); + const deferred = Promise.withResolvers(); + + als.run(null, () => { + const snapshot = AsyncLocalStorage.snapshot(); + als.run({ x: 1 }, () => { + deferred.resolve(snapshot(() => als.getStore())); + }); + }); + + assertEquals(await deferred.promise, null); +}); + +Deno.test(async function bind() { + const als = new AsyncLocalStorage(); + const deferred = Promise.withResolvers(); + + const bound = als.run(null, () => { + return AsyncLocalStorage.bind(() => { + deferred.resolve(als.getStore()); + }); + }); + + als.run({ x: 1 }, () => { + bound(); + }); + + assertEquals(await deferred.promise, null); +}); |