Skip to content

Commit

Permalink
feat: improve AsyncLocalStorage api (#23175)
Browse files Browse the repository at this point in the history
Fixes: #23174
  • Loading branch information
himself65 committed Apr 2, 2024
1 parent c0b7454 commit 8eb2b6c
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
11 changes: 11 additions & 0 deletions ext/node/polyfills/async_hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
31 changes: 31 additions & 0 deletions tests/unit_node/async_hooks_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

0 comments on commit 8eb2b6c

Please sign in to comment.