Skip to content
File

Blob: samples/async-context/worker.js

javascript27 lines
1// Copyright (c) 2022-2023 Cloudflare, Inc.
2// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3// https://opensource.org/licenses/Apache-2.0
4 
5import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
6 
7const als = new AsyncLocalStorage();
8 
9export default {
10 async fetch(request) {
11 const differentScope = als.run(123, () => AsyncResource.bind(() => {
12 console.log(als.getStore());
13 }));
14 
15 return als.run("Hello World", async () => {
16 
17 // differentScope is attached to a different async context, so
18 // it will see a different value for als.getStore() (123)
19 setTimeout(differentScope, 5);
20 
21 // Some simulated async delay.
22 await scheduler.wait(10);
23 return new Response(als.getStore()); // "Hello World"
24 });
25 }
26};