Node.js Domain 模块实例详解
作者:麦叶 时间:2024-05-08 09:35:15
Node.js Domain(域) 简化异步代码的异常处理,可以捕捉处理try catch无法捕捉的异常。
Domain 模块可分为隐式绑定和显式绑定:
隐式绑定: 把在domain上下文中定义的变量,自动绑定到domain对象
显式绑定: 把不是在domain上下文中定义的变量,以代码的方式绑定到domain对象
创建domain.js,代码如下:
var eventEmitter=require("events").EventEmitter;
var domain=require("domain");
var emitter1=new eventEmitter();
//创建域
var domain1=domain.create();
domain1.on("error",function(err){
console.log("domain1来处理这个错误:"+err.message);
})
//显示绑定
domain1.add(emitter1);
//添加emitter1对error的监听
emitter1.on("error",function(err){
console.log("emitter1来处理这个错误:"+err.message);
})
emitter1.emit("error",new Error("触发错误,指定由emitter1处理"));
emitter1.removeAllListeners("error");//移除emitter1对error的监听
emitter1.emit("error",new Error("触发错误,指定由domain1处理"));
//创建域
var domain2=domain.create();
domain2.on("error",function(err){
console.log("domain2来处理这个错误:"+err.message);
})
//隐式绑定
domain2.run(function(){
var emitter2=new eventEmitter();
emitter2.emit("error",new Error("触发错误,指定由domain2处理"));
})
domain1.remove(emitter1);
emitter1.emit("error",new Error("触发错误,系统将崩溃"));
来源:https://www.maiyewang.com/archives/84740
标签:node.js,domain,模块
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Keras框架中的epoch、bacth、batch size、iteration使用介绍
2023-10-13 13:15:13
详细分析Python可变对象和不可变对象
2021-03-10 22:50:10
sqlserver 存储过程带事务 拼接id 返回值
2012-11-30 20:06:39
SQL Server表中添加新列并添加描述
2024-01-23 08:10:17
![](https://img.aspxhome.com/file/2023/2/125702_0s.png)
Python中Parser的超详细用法实例
2022-05-02 10:16:30
asp中判断是否是手机浏览器以及手机类型
2014-12-06 09:33:05
mysql中模糊查询的四种用法介绍
2024-01-23 17:03:02
css基础教程属性篇之盒子模型
2008-07-29 12:05:00
![](https://img.aspxhome.com/file/UploadPic/20087/29/2008729121433524s.jpg)
python 编码规范整理
2023-05-20 10:14:44
python爬取天气数据的实例详解
2022-08-26 22:28:46
![](https://img.aspxhome.com/file/2023/2/68862_0s.png)
MSSQL中递归SQL查询语句实例说明-
2024-01-28 19:54:01
![](https://img.aspxhome.com/file/2023/4/88264_0s.gif)
深入了解javascript中的prototype与继承
2024-04-23 09:13:10
pymongo为mongodb数据库添加索引的方法
2024-01-22 17:51:51
position:relative/absolute无法冲破的等级
2007-05-11 17:03:00
Python实现人脸识别
2022-10-01 06:06:24
![](https://img.aspxhome.com/file/2023/9/80809_0s.png)
vuex mutations的两种调用方法小结
2024-04-27 16:11:42
解决MYSQL出现Can't create/write to file '/tmp/#sql_5c0_0.MYD'的问题
2024-01-16 07:53:39
Python实现好友全头像的拼接实例(推荐)
2021-08-21 17:29:35
![](https://img.aspxhome.com/file/2023/1/75911_0s.jpg)
Golang-如何判断一个 interface{} 的值是否为 nil
2024-02-17 10:08:10
![](https://img.aspxhome.com/file/2023/7/107307_0s.jpg)
python中id函数运行方式
2021-12-27 14:03:50