summaryrefslogtreecommitdiff
path: root/runtime/js/01_async_context.js
blob: 9c0236fbe04aad1a2d9d1241e083d3d61bdf6e4f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// 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;
  }
}