Dev Helpers
← Back

Attach context to a resource

Attach context to a resource using Node.js.

Open this example in the interactive library

Source code

import {
  AsyncLocalStorage,
  AsyncResource,
  executionAsyncId,
} from "node:async_hooks";
const context = new AsyncLocalStorage();
console.log(
  (() => {
    const resource = context.run("resource", () => new AsyncResource("job"));
    try {
      return resource.runInAsyncScope(() => context.getStore());
    } finally {
      resource.emitDestroy();
    }
  })(),
);

Sample output

resource