1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-24 08:09:08 -05:00

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 GitHub
parent c0b7454175
commit 8eb2b6c61f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
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);
});