Async Hook
Node.js async hook
const { AsyncLocalStorage } = require('async_hooks');
const http = require('http');
const asyncLocalStorage = new AsyncLocalStorage();
http.createServer((req, res) => {
// 為每個請求創建特別的 id
const context = { requestId: Date.now() + Math.random() };
// 使用 AsyncLocalStorage.run 給異步操作創建上下文
asyncLocalStorage.run(context, () => {
// mock async action
process.nextTick(() => {
// 在此仍可以訪問上下文
console.log('In process.nextTick:', asyncLocalStorage.getStore());
});
// 使用 setTimeout 模擬延遲
setTimeout(() => {
// 訪問上下文
console.log('In setTimeout:', asyncLocalStorage.getStore());
res.end(`Request handled with id: ${context.requestId}`);
}, 100);
});
}).listen(3000, () => {
console.log('running');
});Last updated