feat: improve AsyncLocalStorage api (#23175)

Fixes: https://github.com/denoland/deno/issues/23174
This commit is contained in:
Alex Yang 2024-04-02 17:53:29 -05:00 committed by Satya Rohith
parent 473212a8b3
commit f4e4e1baaf
No known key found for this signature in database
GPG key ID: B2705CF40523EB05
2 changed files with 42 additions and 0 deletions

View file

@ -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() {

View file

@ -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);
});