Search the reference...
/
BuildDocsReferenceGuidesBlogDiscord/node:async_hooks/AsyncLocalStorage/constructorCoconstructorconstructor
async_hooks.AsyncLocalStorage.constructorNot implemented in Bunconstructor AsyncLocalStorageT>(options?: AsyncLocalStorageOptions): AsyncLocalStorageT>;Creates a new instance of AsyncLocalStorage. Store is only provided within a run() call or after an enterWith() call.Referenced typesinterface AsyncLocalStorageOptionsdefaultValue?: anyThe default value to be used when no store is provided.name?: stringA name for the AsyncLocalStorage value. { 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:58:32
电商商城
成功
标题:可儿莉雅蛋糕裙价格图片精选 - 京东
简介:京东是国内专业的可儿莉雅蛋糕裙网上购物商城,本频道提供可儿莉雅蛋糕裙商品价格信息,可儿莉雅蛋糕裙价格,可儿莉雅蛋糕裙图片
-
2026-03-02 21:51:17
综合导航
成功
标题:Word Detector - Free Online Game on 4J.com
简介:Word Detector is a free online game on 4j.Com. You can find
-
2026-03-02 22:11:55
综合导航
成功
标题:Joseph Williams Blakesley (1808-1885). The Reader's Biographical Encyclopaedia. 1922
简介:Joseph Williams Blakesley (1808-1885). The Reader
-
2026-03-02 17:29:57
综合导航
成功
标题:成婧作文点评_成婧专栏_作文网
简介:成婧专栏提供成婧作文点评、成婧点评作文汇总,包括成婧个人介绍、成婧教学经验、成婧教学成果等,成婧帮孩子写好作文,欢迎踊跃
-
2026-03-02 15:26:13
教育培训
成功
标题:学校生活英语作文九篇
简介:在日常的学习、工作、生活中,大家都写过作文,肯定对各类作文都很熟悉吧,根据写作命题的特点,作文可以分为命题作文和非命题作
-
2026-03-02 19:15:03
实用工具
成功
标题:电脑断电没保存的文件如何恢复 4招技巧快速恢复文件-驱动人生
简介:在日常生活和工作中,电脑已成为我们不可或缺的工具。然而,突如其来的断电往往让人措手不及,尤其是当你正忙着编辑一份重要文件
-
2026-03-02 12:38:56
综合导航
成功
标题:荷兰花海小学作文
简介:在平日的学习、工作和生活里,大家都接触过作文吧,作文是一种言语活动,具有高度的综合性和创造性。你知道作文怎样写才规范吗?
-
2026-03-02 19:10:04
游戏娱乐
成功
标题:万能阿曼涂鸦板,万能阿曼涂鸦板小游戏,4399小游戏 www.4399.com
简介:万能阿曼涂鸦板在线玩,万能阿曼涂鸦板下载, 万能阿曼涂鸦板攻略秘籍.更多万能阿曼涂鸦板游戏尽在4399小游戏,好玩记得告
-
2026-03-02 13:51:41
综合导航
成功
标题:What to watch next week Market focus on February CPI data; Movement public mainnet launch (3.10-3.16) Bee Network
简介:Next weeks highlights March 10 Republican members of the
-
2026-03-02 18:55:27
综合导航
成功
标题:何其芳:哀歌-励志一生
简介:何其芳:哀歌_ 何其芳:哀歌 ……象多雾地带的女子的歌声,她歌唱一个充满了哀愁和爱情的古传说,说着一位公主的不幸,被
-
2026-03-02 14:13:13
教育培训
成功
标题:品味幸福作文15篇【精选】
简介:在平平淡淡的学习、工作、生活中,许多人都写过作文吧,作文是从内部言语向外部言语的过渡,即从经过压缩的简要的、自己能明白的
-
2026-03-02 17:40:15
健康养生
成功
标题:吃哪款益生菌能促进肠道消化吸收?推荐吃这款纽崔莱益生菌 - 谈天说地 - 34楼
简介:肠道是人体消化吸收的核心战场,也是营养输送的第一关卡。三餐不规律、久坐少动、熬夜压力大、高油高糖饮食,正在让越来越多女性
-
2026-03-02 16:19:53
综合导航
成功
标题:昭华未央全文免费阅读最新章节_昭华未央全文免费阅读全文免费阅读_恋上你看书网
简介:去他的天地君亲,她只要以直报怨。女主非重生,非穿越,土著伪白花。设定略雷,道德洁癖者慎入,架空朝代,考据者慎入。接编辑通
-
2026-03-02 17:06:52
综合导航
成功
标题:property percentilesBigInt Node.js perf_hooks module Bun
简介:Returns a `Map` object detailing the accumulated percentile
-
2026-03-02 21:45:06
电商商城
成功
标题:金妮儿女童中长款羽绒服预订订购价格 - 京东
简介:京东是国内专业的金妮儿女童中长款羽绒服网上购物商城,本频道提供金妮儿女童中长款羽绒服商品预订订购价格,金妮儿女童中长款羽
-
2026-03-02 12:41:19
综合导航
成功
标题:2E Смарт-годинник Alpha SQ Music Edition 46mm Black-Green (217214794) - RIA
简介:Продаю на RIA - 2E Смарт-годинник Alpha SQ Music Edition 46m
-
2026-03-02 20:57:13
游戏娱乐
成功
标题:攻其不备 游戏截图截图_攻其不备 游戏截图壁纸_攻其不备 游戏截图图片_3DM单机
简介:攻其不备 游戏截图截图_攻其不备 游戏截图壁纸_攻其不备 游戏截图图片_3DM单机
-
2026-03-02 20:57:42
综合导航
成功
标题:Industry Terms: Accreditations Inspiring Workspaces by BOS
简介:Accreditations are important for quality, competency and cap
-
2026-03-02 18:55:31
综合导航
成功
标题:缩字的意思_缩字的解释、组词、拼音、组词、笔顺、部首-雄安文学网
简介:雄安文学网为您提供【缩】字的详细解释,包括【缩】组词、拼音、组词、笔顺、部首和笔画,帮助您全面理解和掌握【缩】的含义和用
-
2026-03-02 16:08:38
视频影音
成功
标题:安全防护软件,安全防护软件下载,安全防护软件大全,第1页,绿色软件、工具、免费软件、共享软件-160软件
简介:160软件为您提供各种最新的安全防护软件下载,想知道安全防护软件哪个好,什么安全防护软件最好用,就上160软件。160软
-
2026-03-02 20:47:43
综合导航
成功
标题:夜晚游玩作文
简介:在平平淡淡的日常中,大家对作文都再熟悉不过了吧,借助作文可以宣泄心中的情感,调节自己的心情。一篇什么样的作文才能称之为优
-
2026-03-02 14:11:06
图片素材
成功
标题:仿写的作文1500字 描写仿写的作文 关于仿写的作文-作文网
简介:作文网精选关于仿写的1500字作文,包含仿写的作文素材,关于仿写的作文题目,以仿写为话题的1500字作文大全,作文网原创
-
2026-03-02 21:47:24
综合导航
成功
标题:ç»å²¸çæ¼é³_ç»å²¸çææ_ç»å²¸çç¹ä½_è¯ç»ç½
简介:è¯ç»ç½ç»å²¸é¢é,ä»ç»ç»å²¸,ç»å²¸çæ¼é³,ç»å²¸æ¯
-
2026-03-02 13:54:47
综合导航
成功
标题:3SGTE Fully Prepped Head - $2,700 [Archive] - Toyota MR2 Message Board
简介:This is a Gen II 3SGTE head.The head has the following upgra
-
2026-03-02 22:20:59
电商商城
成功
标题:【京东优评】热卖商品_优质评价排行、看实拍买好货 - 京东
简介:京东优评频道,为用户提供真实、专业的商品评价排行榜,包含商品价格、图片、品牌、优惠券、商品怎么样等多维度信息,精选用户购
-
2026-03-02 22:02:02
游戏娱乐
成功
标题:乳牙21_禁闭求生2所有乳牙怎么获得-Grounded2全乳牙获得方法介绍_3DM单机
简介:《禁闭求生2》中的乳牙是游戏里非常重要的特殊材料,而乳牙可以分为普通乳牙和巨型乳牙,一共有三十一颗常规乳牙和十八颗巨型乳
-
2026-03-02 19:25:55
综合导航
成功
标题:星空第一害虫目录最新章节_星空第一害虫全文免费阅读_风云中文网
简介:星空第一害虫目录最新章节由网友提供,《星空第一害虫》情节跌宕起伏、扣人心弦,是一本情节与文笔俱佳的风云中文网,风云中文网
-
2026-03-02 14:13:50
教育培训
成功
标题:我的奶奶作文
简介:在生活、工作和学习中,大家都经常接触到作文吧,借助作文可以提高我们的语言组织能力。相信许多人会觉得作文很难写吧,以下是小
-
2026-03-02 12:54:41
综合导航
成功
标题:属相 第17页 - 吉吉算命网
简介:属相 第17页_吉吉算命网
-
2026-03-02 16:26:26
综合导航
成功
标题:1800-01220 Change over unit cock - VTE-FILTER GmbH
简介:Fabricante: Alfa Laval Moatti N.º OEM: Alfa Laval Moatti coc