diff --git a/samples/node-async-hooks/node-async-hooks.js b/samples/node-async-hooks/node-async-hooks.js new file mode 100644 index 00000000..9c561806 --- /dev/null +++ b/samples/node-async-hooks/node-async-hooks.js @@ -0,0 +1,33 @@ +import { AsyncLocalStorage } from "node:async_hooks"; + +const requestId = new AsyncLocalStorage(); + +async function logAsyncContext(state) { + console.log(`${requestId.getStore()} - ${state}`); +} + +async function doSomething() { + logAsyncContext("log from async function"); + doSomethingElse(); +} + +async function doSomethingElse() { + logAsyncContext("log from another async function"); +} + +async function handleRequest(request) { + const id = request.headers.get("X-Request-Id"); + + return requestId.run(id, async () => { + doSomething(); + logAsyncContext("log from yet another async function"); + requestId.exit(async () => { + logAsyncContext("log from exit callback"); + }); + return new Response("ok"); + }); +} + +addEventListener("fetch", (event) => { + event.respondWith(handleRequest(event.request)); +}); \ No newline at end of file diff --git a/samples/node-async-hooks/readme.md b/samples/node-async-hooks/readme.md new file mode 100644 index 00000000..178a4f2b --- /dev/null +++ b/samples/node-async-hooks/readme.md @@ -0,0 +1,22 @@ +# Node.js Async Hooks and Edge Functions + +This is an example of using **Node.js Async Hooks**, specifically the **AsyncLocalStorage API**, to manage context within asynchronous operations inside an edge function. + +## Code Overview + +The code consists of several asynchronous functions (**doSomething**, **doSomethingElse**, **handleRequest**) that simulate different parts of a request-handling process. + +The AsyncLocalStorage instance, **requestId**, is used to store and retrieve a request-specific value (in this case, a request ID from headers) across these asynchronous operations. + +Here's a brief description of the functions: + +- logAsyncContext(state): logs the current request ID and a state message to the console. +- doSomething(): simulates an asynchronous operation and logs its context. +- doSomethingElse(): simulates another asynchronous operation and logs its context. +- handleRequest(request): handles an incoming request, retrieves the request ID from the headers, and runs a series of asynchronous operations within the context of this request ID. + +The handleRequest function is registered as an event listener for fetch events, meaning it'll be invoked for every incoming request. + +## Usage + +This code is designed to run on **Azion Edge Runtime** and demonstrates how to use AsyncLocalStorage to maintain context across asynchronous operations. It can be particularly useful in scenarios such as request handling in a web server, where you might need to keep track of request-specific data across multiple asynchronous operations. \ No newline at end of file