Search the reference...
/
BuildDocsReferenceGuidesBlogDiscord/node:async_hooks/AsyncLocalStorageMbindCoconstructorMdisableMenterWithMexitMgetStorePnameMrunMsnapshotclass
async_hooks.AsyncLocalStorage { asyncLocalStorage.run(idSeq++, () => { logWithId('start'); // Imagine any chain of async operations here setImmediate(() => { logWithId('finish'); res.end(); }); }); }).listen(8080); http.get('http://localhost:8080'); http.get('http://localhost:8080'); // Prints: // 0: start // 0: finish // 1: start // 1: finish ``` Each instance of `AsyncLocalStorage` maintains an independent storage context. Multiple instances can safely exist simultaneously without risk of interfering with each other's data." data-algolia-static="false" data-algolia-merged="false" data-type="Class">class AsyncLocalStorageT>This class creates stores that stay coherent through asynchronous operations.While you can create your own implementation on top of the node:async_hooks module, AsyncLocalStorage should be preferred as it is a performant and memory safe implementation that involves significant optimizations that are non-obvious to implement.The following example uses AsyncLocalStorage to build a simple logger that assigns IDs to incoming HTTP requests and includes them in messages logged within each request.import http from 'node:http'; import { AsyncLocalStorage } from 'node:async_hooks'; const asyncLocalStorage = new AsyncLocalStorage(); function logWithId(msg) { const id = asyncLocalStorage.getStore(); console.log(`${id !== undefined ? id : '-'}:`, msg); } let idSeq = 0; http.createServer((req, res) => { asyncLocalStorage.run(idSeq++, () => { logWithId('start'); // Imagine any chain of async operations here setImmediate(() => { logWithId('finish'); res.end(); }); }); }).listen(8080); http.get('http://localhost:8080'); http.get('http://localhost:8080'); // Prints: // 0: start // 0: finish // 1: start // 1: finish Each instance of AsyncLocalStorage maintains an independent storage context. Multiple instances can safely exist simultaneously without risk of interfering with each other's data.readonly name: stringThe name of the AsyncLocalStorage instance if provided.disable(): void;Disables the instance of AsyncLocalStorage. All subsequent calls to asyncLocalStorage.getStore() will return undefined until asyncLocalStorage.run() or asyncLocalStorage.enterWith() is called again.When calling asyncLocalStorage.disable(), all current contexts linked to the instance will be exited.Calling asyncLocalStorage.disable() is required before the asyncLocalStorage can be garbage collected. This does not apply to stores provided by the asyncLocalStorage, as those objects are garbage collected along with the corresponding async resources.Use this method when the asyncLocalStorage is not in use anymore in the current process. { asyncLocalStorage.getStore(); // Returns the same object }); ``` This transition will continue for the _entire_ synchronous execution. This means that if, for example, the context is entered within an event handler subsequent event handlers will also run within that context unless specifically bound to another context with an `AsyncResource`. That is why `run()` should be preferred over `enterWith()` unless there are strong reasons to use the latter method. ```js const store = { id: 1 }; emitter.on('my-event', () => { asyncLocalStorage.enterWith(store); }); emitter.on('my-event', () => { asyncLocalStorage.getStore(); // Returns the same object }); asyncLocalStorage.getStore(); // Returns undefined emitter.emit('my-event'); asyncLocalStorage.getStore(); // Returns the same object ```" data-algolia-static="false" data-algolia-merged="false" data-type="Method">enterWith(store: T): void;Transitions into the context for the remainder of the current synchronous execution and then persists the store through any following asynchronous calls.Example:const store = { id: 1 }; // Replaces previous store with the given store object asyncLocalStorage.enterWith(store); asyncLocalStorage.getStore(); // Returns the store object someAsyncOperation(() => { asyncLocalStorage.getStore(); // Returns the same object }); This transition will continue for the entire synchronous execution. This means that if, for example, the context is entered within an event handler subsequent event handlers will also run within that context unless specifically bound to another context with an AsyncResource. That is why run() should be preferred over enterWith() unless there are strong reasons to use the latter method.const store = { id: 1 }; emitter.on('my-event', () => { asyncLocalStorage.enterWith(store); }); emitter.on('my-event', () => { asyncLocalStorage.getStore(); // Returns the same object }); asyncLocalStorage.getStore(); // Returns undefined emitter.emit('my-event'); asyncLocalStorage.getStore(); // Returns the same object { asyncLocalStorage.getStore(); // Returns undefined throw new Error(); }); } catch (e) { asyncLocalStorage.getStore(); // Returns the same object or value // The error will be caught here } ```" data-algolia-static="false" data-algolia-merged="false" data-type="Method">exitR, TArgs extends any[]>(callback: (...args: TArgs) => R,...args: TArgs): R;Runs a function synchronously outside of a context and returns its return value. The store is not accessible within the callback function or the asynchronous operations created within the callback. Any getStore() call done within the callback function will always return undefined.The optional args are passed to the callback function.If the callback function throws an error, the error is thrown by exit() too. The stacktrace is not impacted by this call and the context is re-entered.Example:// Within a call to run try { asyncLocalStorage.getStore(); // Returns the store object or value asyncLocalStorage.exit(() => { asyncLocalStorage.getStore(); // Returns undefined throw new Error(); }); } catch (e) { asyncLocalStorage.getStore(); // Returns the same object or value // The error will be caught here } getStore(): undefined | T;Returns the current store. If called outside of an asynchronous context initialized by calling asyncLocalStorage.run() or asyncLocalStorage.enterWith(), it returns undefined. { asyncLocalStorage.getStore(); // Returns the store object setTimeout(() => { asyncLocalStorage.getStore(); // Returns the store object }, 200); throw new Error(); }); } catch (e) { asyncLocalStorage.getStore(); // Returns undefined // The error will be caught here } ```" data-algolia-static="false" data-algolia-merged="false" data-type="Method">runR>(store: T,callback: () => R): R;Runs a function synchronously within a context and returns its return value. The store is not accessible outside of the callback function. The store is accessible to any asynchronous operations created within the callback.The optional args are passed to the callback function.If the callback function throws an error, the error is thrown by run() too. The stacktrace is not impacted by this call and the context is exited.Example:const store = { id: 2 }; try { asyncLocalStorage.run(store, () => { asyncLocalStorage.getStore(); // Returns the store object setTimeout(() => { asyncLocalStorage.getStore(); // Returns the store object }, 200); throw new Error(); }); } catch (e) { asyncLocalStorage.getStore(); // Returns undefined // The error will be caught here } runR, TArgs extends any[]>(store: T,callback: (...args: TArgs) => R,...args: TArgs): R;Runs a function synchronously within a context and returns its return value. The store is not accessible outside of the callback function. The store is accessible to any asynchronous operations created within the callback.The optional args are passed to the callback function.If the callback function throws an error, the error is thrown by run() too. The stacktrace is not impacted by this call and the context is exited.Example:const store = { id: 2 }; try { asyncLocalStorage.run(store, () => { asyncLocalStorage.getStore(); // Returns the store object setTimeout(() => { asyncLocalStorage.getStore(); // Returns the store object }, 200); throw new Error(); }); } catch (e) { asyncLocalStorage.getStore(); // Returns undefined // The error will be caught here } static bindFunc extends (...args: any[]) => any>(fn: Func): Func;Binds the given function to the current execution context.@param fnThe function to bind to the current execution context.@returnsA new function that calls fn within the captured execution context. AsyncLocalStorage.snapshot()); const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); console.log(result); // returns 123 ``` AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple async context tracking purposes, for example: ```js class Foo { #runInAsyncScope = AsyncLocalStorage.snapshot(); get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } } const foo = asyncLocalStorage.run(123, () => new Foo()); console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 ```" data-algolia-static="true" data-algolia-merged="false" data-type="Method">static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R;Captures the current execution context and returns a function that accepts a function as an argument. Whenever the returned function is called, it calls the function passed to it within the captured context.const asyncLocalStorage = new AsyncLocalStorage(); const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); console.log(result); // returns 123 AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple async context tracking purposes, for example:class Foo { #runInAsyncScope = AsyncLocalStorage.snapshot(); get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } } const foo = asyncLocalStorage.run(123, () => new Foo()); console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 @returnsA new function with the signature (fn: (...args) : R, ...args) : R.Resources
ReferenceDocsGuidesDiscordMerch StoreGitHubBlogToolkit
RuntimePackage managerTest runnerBundlerPackage runnerProject
Bun 1.0Bun 1.1Bun 1.2Bun 1.3RoadmapContributingLicenseBaked with ❤️ in San FranciscoWe're hiring →智能索引记录
-
2026-03-02 20:04:56
游戏娱乐
成功
标题:青蛙上百层,青蛙上百层小游戏,4399小游戏 www.4399.com
简介:青蛙上百层在线玩,青蛙上百层下载, 青蛙上百层攻略秘籍.更多青蛙上百层游戏尽在4399小游戏,好玩记得告诉你的朋友哦!
-
2026-03-02 10:09:11
宠物用品
成功
标题:浙江宠物除味剂配方还原/检测哪家专业-北京孤凡电子商务有限公司
简介:配方还原与检测并非标准化流程,而是高度依赖样品特性与分析目标的定制化服务。不同行业、不同材料的分析需求差异明显,因此需要
-
2026-03-02 11:41:28
综合导航
成功
标题:成语的四字词语_成语式词语大全_词组网
简介:词组网成语的词语频道,介绍成语的四字词语,成语式词语大全,成语有哪些,成语的词语用法,学组词,涨知识,词组网,传文化。
-
2026-03-02 13:05:45
综合导航
成功
标题:Eyelid. World English Historical Dictionary
简介:Eyelid. World English Historical Dictionary
-
2026-03-02 20:49:35
综合导航
成功
标题:WTB: Gen3 R-134a AC compressor [Archive] - Toyota MR2 Message Board
简介:I
-
2026-03-02 18:42:33
综合导航
成功
标题:ä¸èèé£ï¼ä¸ç»èè¡£çæ¼é³_ä¸èèé£ï¼ä¸ç»èè¡£çææ_ä¸èèé£ï¼ä¸ç»èè¡£çç¹ä½_è¯ç»ç½
简介:è¯ç»ç½ä¸èèé£ï¼ä¸ç»èè¡£é¢é,ä»ç»ä¸èèé£
-
2026-03-02 19:00:44
综合导航
成功
标题:AI智能索引 - AI智能索引
简介:AI智能索引 - 提供全网公开链接智能索引服务,快速访问目标内容,支持分类筛选和智能导航
-
2026-03-02 20:44:33
游戏娱乐
成功
标题:动作小游戏,4399动作类小游戏,动作小游戏大全,4399小游戏
简介:4399动作小游戏大全收录国内外动作类小游戏,动作类游戏,动作类网页游戏,双人动作小游戏,动作小游戏下载,动作小游戏排行
-
2026-03-02 12:16:24
综合导航
成功
标题:我的朋友作文400个字
简介:小编:欢迎阅读与支持,如果喜欢记得常来!内容简介:我有一个朋友叫杨林瑞,他中等个子,身子瘦瘦的,一张白净的瓜子脸,夏天他
-
2026-03-02 11:33:05
综合导航
成功
标题:《联邦调查局第四季》在线观看-迅雷下载-最新美剧-美剧网
简介:联邦调查局第四季剧情介绍:联邦调查局第四季是由艾利克斯·查普执导,梅西·帕瑞格兰,阿兰娜·德拉·伽兹,Roshawn F
-
2026-03-02 20:12:45
综合导航
成功
标题:ENS Vision Bee Network
简介:Thị trường tên miền ENS
-
2026-03-02 18:39:12
游戏娱乐
成功
标题:古罗马比武场2,古罗马比武场2小游戏,4399小游戏 www.4399.com
简介:古罗马比武场2在线玩,古罗马比武场2下载, 古罗马比武场2攻略秘籍.更多古罗马比武场2游戏尽在4399小游戏,好玩记得告
-
2026-03-02 10:18:09
综合导航
成功
标题:Schaeffler Germany
简介:Schaeffler has been driving forward groundbreaking invention
-
2026-03-02 20:52:04
数码科技
成功
标题:从"看得见"到"能干活",机器人的下一步是拥有触觉 传感器 光场 动作 机器人 视觉 触觉_手机网易网
简介:机器人的下一步是拥有触觉吗
-
2026-03-02 20:01:08
电商商城
成功
标题:hardaway中轴倒置三脚架/云台怎么样 - 京东
简介:京东是专业的hardaway中轴倒置三脚架/云台网上购物商城,为您提供hardaway中轴倒置三脚架/云台价格图片信息、
-
2026-03-02 18:40:00
游戏娱乐
成功
标题:格蕾丝-打开顶棚让光照射“女孩”(本章完 明天先推图 下午会更新)_生化危机9安魂曲全流程图文攻略-图文流程攻略_3DM单机
简介:《生化危机9:安魂曲》是生化危机开创生存恐怖新纪元的系列最新作。我们与FBI分析员格蕾丝一同体验令人战栗的恐惧,并与资深
-
2026-03-02 12:17:22
教育培训
成功
标题:油菜花作文(精选11篇)
简介:在日常学习、工作或生活中,大家都写过作文,肯定对各类作文都很熟悉吧,借助作文人们可以反映客观事物、表达思想感情、传递知识
-
2026-03-02 19:16:58
电商商城
成功
标题:轻装时代q278新款 - 轻装时代q2782021年新款 - 京东
简介:京东是国内专业的轻装时代q278网上购物商城,本频道提供轻装时代q278新款价格、轻装时代q278新款图片信息,为您选购
-
2026-03-02 10:23:01
综合导航
成功
标题:Marcel Ahrens
简介:1x.com is the world
-
2026-03-02 12:59:28
视频影音
成功
标题:逆袭从签到神级姐姐开始第79集河马短剧_在线播放[高清流畅]_爽文短剧
简介:爽文短剧_逆袭从签到神级姐姐开始剧情介绍:逆袭从签到神级姐姐开始是由内详执导,内详等人主演的,于2025年上映,该都市讲
-
2026-03-02 10:26:10
教育培训
成功
标题:徒子徒孙的意思解释_徒子徒孙是什么意思-雄安文学网
简介:徒子徒孙是什么意思?雄安文学网为您提供徒子徒孙的意思解释、拼音、近反义词,以及徒子徒孙成语接龙,供成语爱好者参考学习用。
-
2026-03-02 14:03:40
综合导航
成功
标题:Angry Families Want GM Prosecuted for Defects Law.com
简介:The families of those who died in General Motors cars with d
-
2026-03-02 14:01:45
教育培训
成功
标题:美丽的小学作文6篇【实用】
简介:在日复一日的学习、工作或生活中,大家都跟作文打过交道吧,作文要求篇章结构完整,一定要避免无结尾作文的出现。那么问题来了,
-
2026-03-02 19:59:33
数码科技
成功
标题:电脑前面的插孔没声音怎么设置 试试这5个方法-驱动人生
简介:本文介绍了电脑前面的插孔没声音的设置方法,帮助用户快速恢复电脑声音。
-
2026-03-02 22:27:06
电商商城
成功
标题:电风扇 水田型号规格 - 京东
简介:京东是国内专业的电风扇 水田网上购物商城,本频道提供电风扇 水田型号、电风扇 水田规格信息,为您选购电风扇 水田型号规格
-
2026-03-02 19:10:05
电商商城
成功
标题:纳伽4节三脚架/云台 - 京东
简介:京东是国内专业的纳伽4节三脚架/云台网上购物商城,本频道提供纳伽4节三脚架/云台商品图片,纳伽4节三脚架/云台价格,纳伽
-
2026-03-02 18:49:18
综合导航
成功
标题:徒儿下山祸害你师姐去吧陈楠最新章节_第1章 我为山上流过血第1页_徒儿下山祸害你师姐去吧陈楠免费阅读_恋上你看书网
简介:第1章 我为山上流过血第1页_徒儿下山祸害你师姐去吧陈楠_鳄鱼皮带_恋上你看书网
-
2026-03-02 13:56:25
数码科技
成功
标题:美漫丧钟第1762章 精神病院_美漫丧钟_混沌文工团_十二小说网_规则类怪谈扮演指南
简介:美漫丧钟最新章节第1762章 精神病院出自混沌文工团的作品美漫丧钟最新章节每天第一时间更新。美漫丧钟txt电子书下载,最
-
2026-03-02 11:56:48
美妆护肤
成功
标题:秋天15分钟紧急补水嫩肤 - 豆丁网
简介:秋天15分钟紧急补水嫩肤,秋天皮肤干燥这是一种普遍现象,只要使用补水面膜或是保湿乳液,干燥会有所缓解,脱皮的症状也会远离
-
2026-03-02 13:07:50
电商商城
成功
标题:京东597网怎么样 - 京东
简介:京东是专业的京东597网网上购物商城,为您提供京东597网价格图片信息、京东597网怎么样的用户评论、京东597网精选导