1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-08 23:28:18 -05:00
denoland-deno/runtime/js/01_async_context.js
snek 3a1a1cc030
feat: async context (#24402)
We are switching to ContinuationPreservedEmbedderData. This allows
adding async context tracking to the various async operations that deno
provides.

Fixes: https://github.com/denoland/deno/issues/7010
Fixes: https://github.com/denoland/deno/issues/22886
Fixes: https://github.com/denoland/deno/issues/24368
2024-08-02 08:14:35 -07:00

45 lines
1.1 KiB
JavaScript

// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
import { primordials } from "ext:core/mod.js";
import { op_get_extras_binding_object } from "ext:core/ops";
const {
SafeWeakMap,
} = primordials;
const {
getContinuationPreservedEmbedderData,
setContinuationPreservedEmbedderData,
} = op_get_extras_binding_object();
let counter = 0;
export const getAsyncContext = getContinuationPreservedEmbedderData;
export const setAsyncContext = setContinuationPreservedEmbedderData;
export class AsyncVariable {
#id = counter++;
#data = new SafeWeakMap();
enter(value) {
const previousContextMapping = getAsyncContext();
const entry = { id: this.#id };
const asyncContextMapping = {
__proto__: null,
...previousContextMapping,
[this.#id]: entry,
};
this.#data.set(entry, value);
setAsyncContext(asyncContextMapping);
return previousContextMapping;
}
get() {
const current = getAsyncContext();
const entry = current?.[this.#id];
if (entry) {
return this.#data.get(entry);
}
return undefined;
}
}