作家
登录

[译]理解Node.js事件驱动机制

作者: 来源: 2017-08-16 12:04:42 阅读 我要评论

第一次调用 execute 将会触发 error 事宜,因为没有处理 error ,Node 法度榜样随之崩溃:

  1. events.js:163 
  2.       throw er; // Unhandled 'error' event 
  3.       ^ 
  4. Error: ENOENT: no such file or directory, open ''  
  1. class WithTime extends EventEmitter { 
  2.   async execute(asyncFunc, ...args) { 
  3.     this.emit('begin'); 
  4.     try { 
  5.       console.time('execute'); 
  6.       const data = await asyncFunc(...args); 
  7.       this.emit('data', data); 
  8.       console.timeEnd('execute'); 
  9.       this.emit('end'); 
  10.     } catch(err) { 
  11.       this.emit('error', err); 
  12.     } 
  13.   } 
  14.  

第二次履行调用将受到此崩溃的影响,并且可能根本不会被履行。

如不雅我们为这个 error 事宜注册一个监听器函数来处理 error,结不雅将大年夜不雷同:

  1. withTime.on('error', (err) => { 
  2.  
  3.   // do something with err, for example log it somewhere 
  4.  
  5.   console.log(err) 
  6.  
  7. });  

如不雅我们履行上述操作,将会申报第一次履行 execute 时发送的缺点,然则此次 node 过程不会崩溃退出,其他法度榜样的调用也都能正常完成:

  1. { Error: ENOENT: no such file or directory, open '' errno: -2, code: 'ENOENT', syscall: 'open', path: '' } 
  2. execute: 4.276ms  

须要留意的是,基于 Promise 的函数有些不合,它们临时只是输出一个警告:

data 事宜被触发时会携带一个 data 对象。

  1. UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: ENOENT: no such file or directory, open '' 
  2.  
  3. DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with

      推荐阅读

      反腐有了大数据“侦探”

    市纪委经由过程对大年夜数据云与干部填报的家庭房产等情况的量化数据比对,敏捷排查出漏报瞒报人员,进而大年夜干部工作、生活相干事项着手,抓早抓小、大年夜严监管,教导抢救了大年夜批干部,起到了强大年夜的教导>>>详细阅读


    本文标题:[译]理解Node.js事件驱动机制

    地址:http://www.17bianji.com/lsqh/36743.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)