今天有同事问我下面这段代码是什么意思:

var MyClass = function() {
events.EventEmitter.call(this); // 这行是什么意思?
};
util.inherits(MyClass, events.EventEmitter); // 还有这行?

  我也不是很明白,于是研究了一下。下面是我的一些体会。

Christmas Trees和Errors

  如果你写过JavaScript或NodeJS代码,你也许会对callback地狱深有体会。每次当你进行异步调用时,按照callback的契约,你需要传一个function作为回调函数,function的第一个参数则默认为接收的error。这是一个非常棒的约定,不过仍然存在两个小问题:

  1. 每次回调过程中都需要检查是否存在error - 这很烦人

  2. 每一次的回调都会使代码向右缩进,如果回调的层级很多,则我们的代码看起来就像圣诞树一样:

  此外,如果每个回调都是一个匿名函数并包含大量的代码,那么维护这样的代码将会使人抓狂。

你会怎么做呢?

  其实有许多方法都可以解决这些问题,下面我将提供三种不同方式编写的代码用于说明它们之间的区别。

  1. 标准回调函数

  2. Event Emitter

  3. Promises

  我创建了一个简单的类"User Registration",用于将email保存到数据库并发送。在每个示例中,我都假设save操作成功,发送email操作失败。

  1)标准回调函数

  前面已经提过,NodeJS对回调函数有一个约定,那就是error在前,回调在后。在每一次回调中,如果出现错误,你需要将错误抛出并截断余下的回调操作。

########################### registration.js #################################
var Registration = function () {
if (!(this instanceof Registration)) return new Registration();
var _save = function (email, callback) {
setTimeout(function(){
callback(null);
}, 20);
};
var _send = function (email, callback) {
setTimeout(function(){
callback(new Error("Failed to send"));
}, 20);
};
this.register = function (email, callback) {
_save(email, function (err) {
if (err)
return callback(err);
_send(email, function (err) {
callback(err);
});
});
};
};
module.exports = Registration;
########################### app.js #################################
var Registration = require('./registration.js');
var registry = new Registration();
registry.register("john@example.com", function (err) {
console.log("done", err);
});

  大部分时候我还是倾向于使用标准回调函数。如果你觉得你的代码结构看起来很清晰,那么我不认为"Christmas Tree"会对我产生太多的困扰。回调中的error检查会有点烦人,不过代码看起来很简单。

  2)Event Emitter

  在NodeJS中,有一个内置的库叫EventEmitter非常不错,它被广泛应用到NodeJS的整个系统中。

  你可以创建emitter的一个实例,不过更常见的做法是从emitter继承,这样你可以订阅从特定对象上产生的事件。

  最关键的是我们可以将事件连接起来变成一种工作流如“当email被成功保存之后就立刻发送”。

  此外,名为error的事件有一种特殊的行为,当error事件没有被任何对象订阅时,它将在控制台打印堆栈跟踪信息并退出整个进程。也就是说,未处理的errors会使整个程序崩掉。

########################### registration.js #################################
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var Registration = function () {
//call the base constructor
EventEmitter.call(this);
var _save = function (email, callback) {
this.emit('saved', email);
};
var _send = function (email, callback) {
//or call this on success: this.emit('sent', email);
this.emit('error', new Error("unable to send email"));
};
var _success = function (email, callback) {
this.emit('success', email);
};
//the only public method
this.register = function (email, callback) {
this.emit('beginRegistration', email);
};
//wire up our events
this.on('beginRegistration', _save);
this.on('saved', _send);
this.on('sent', _success);
};
//inherit from EventEmitter
util.inherits(Registration, EventEmitter);
module.exports = Registration;
########################### app.js #################################
var Registration = require('./registration.js');
var registry = new Registration();
//if we didn't register for 'error', then the program would close when an error happened
registry.on('error', function(err){
console.log("Failed with error:", err);
});
//register for the success event
registry.on('success', function(){
console.log("Success!");
});
//begin the registration
registry.register("john@example.com");

  你可以看到上面的代码中几乎没有什么嵌套,而且我们也不用像之前那样在回调函数中去检查errors。如果有错误发生,程序将抛出错误信息并绕过余下的注册过程。

  3)Promises

  这里有大量关于promises的说明,如promises-spec, common-js等等。下面是我的理解。

  Promises是一种约定,它使得对嵌套回调和错误的管理看起来更加优雅。例如异步调用一个save方法,我们不用给它传递回调函数,该方法将返回一个promise对象。这个对象包含一个then方法,我们将callback函数传递给它以完成回调函数的注册。

  据我所知,人们倾向于使用标准回调函数的形式来编写代码,然后使用如deferred的库来将这些回调函数转换成promise的形式。这正是我在这里要做的。

######################### app.js ############################
var Registration = require('./registration.js');
var registry = new Registration();
registry.register("john@example.com")
.then(
function () {
console.log("Success!");
},
function (err) {
console.log("Failed with error:", err);
}
);
######################### registration.js ############################
var deferred = require('deferred');
var Registration = function () {
//written as conventional callbacks, then converted to promises
var _save = deferred.promisify(function (email, callback) {
callback(null);
});
var _send = deferred.promisify(function (email, callback) {
callback(new Error("Failed to send"));
});
this.register = function (email, callback) {
//chain two promises together and return a promise
return _save(email)
.then(_send);
};
};
module.exports = Registration;

  promise消除了代码中的嵌套调用以及像EventEmitter那样传递error。这里我列出了它们之间的一些区别:

  EventEmitter

  • 需要引用util和events库,这两个库已经包含在NodeJS中
  • 你需要将自己的类从EventEmitter继承
  • 如果error未处理则会抛出运行时异常
  • 支持发布/订阅模式

  Promise

  • 使整个回调形成一个链式结构
  • 需要库的支持来将回调函数转换成promise的形式,如deferred或Q
  • 会带来更多的开销,所以可能会稍微有点慢
  • 不支持发布/订阅模式

原文地址:http://www.joshwright.com/tips/javascript-christmas-trees-promises-and-event-emitters

Christmas Trees, Promises和Event Emitters的更多相关文章

  1. [LeetCode] Cut Off Trees for Golf Event 为高尔夫赛事砍树

    You are asked to cut off trees in a forest for a golf event. The forest is represented as a non-nega ...

  2. [Swift]LeetCode675. 为高尔夫比赛砍树 | Cut Off Trees for Golf Event

    You are asked to cut off trees in a forest for a golf event. The forest is represented as a non-nega ...

  3. LeetCode - Cut Off Trees for Golf Event

    You are asked to cut off trees in a forest for a golf event. The forest is represented as a non-nega ...

  4. LeetCode 675. Cut Off Trees for Golf Event

    原题链接在这里:https://leetcode.com/problems/cut-off-trees-for-golf-event/description/ 题目: You are asked to ...

  5. [LeetCode] 675. Cut Off Trees for Golf Event 为高尔夫赛事砍树

    You are asked to cut off trees in a forest for a golf event. The forest is represented as a non-nega ...

  6. 675. Cut Off Trees for Golf Event

    // Potential improvements: // 1. we can use vector<int> { h, x, y } to replace Element, sortin ...

  7. codeforces 1283D. Christmas Trees(bfs)

    链接: https://codeforces.com/contest/1283/problem/D 题意:给定n个不同的整数点,让你找m个不同的整数点,使得这m个点到到这n个点最小距离之和最小. 思路 ...

  8. Gulp自动化构建的基本使用

    Study Notes 本博主会持续更新各种前端的技术,如果各位道友喜欢,可以关注.收藏.点赞下本博主的文章. Gulp 用自动化构建工具增强你的工作流程! gulp 将开发流程中让人痛苦或耗时的任务 ...

  9. 【POJ3710】Christmas Game (博弈-树上的删边问题)

    [题目] Description Harry and Sally were playing games at Christmas Eve. They drew some Christmas trees ...

随机推荐

  1. 4.View绘制分析笔记之onDraw

    上一篇文章我们了解了View的onLayout,那么今天我们来学习Android View绘制三部曲的最后一步,onDraw,绘制. ViewRootImpl#performDraw private ...

  2. 学习微信小程序之css3display

    一display diaplay改变标签的模式,行内装块级(block),块级转行内(inline) 通过设置display为none,可以 让整个标签在页内移除掉 设置visibility为hidd ...

  3. Spring 自带的定时任务

    需要几天后,或者某个时间后,定时查询数据.需要用到Spring自带的一个注解 @Scheduled(cron="0/5 * * * * ? ")//每隔5秒钟执行 创建一个clas ...

  4. phoneGap蓝牙设备链接打印操作插件

    前台 bluetooth.js /*Copyright 2013  101.key Licensed under the Apache License, Version 2.0 (the " ...

  5. 跨界玩AR,迪奥、Hugo Boss等知名奢侈品牌将制造AR眼镜

    Snapchat因为阅后即焚消息应用而被人所熟知,前段时间这家公司拓展主要业务,未来将不再只有消息应用,还有款名为"Spectacles"的AR太阳镜.内置了一个摄像头,戴上之后即 ...

  6. CS0103: The name ‘Scripts’ does not exist in the current context解决方法

    转至:http://blchen.com/cs0103-the-name-scripts-does-not-exist-in-the-current-context-solution/ 更新:这个bu ...

  7. linu for循环

    用途说明 在shell中用于循环.类似于其他编程语言中的for,但又有些不同.for循环是Bash中最常用的语法结构. 常用格式 格式一 for 变量 do 语句 done 格式二 for 变量 in ...

  8. 《JavaScript高级程序设计(第3版)》阅读总结记录第一章之JavaScript简介

    前言: 为什么会想到把<JavaScript 高级程序设计(第 3 版)>总结记录呢,之前写过一篇博客,研究的轮播效果,后来又去看了<JavaScript 高级程序设计(第3版)&g ...

  9. IDEA插件

    Key Promoter 快捷键提示插件,帮助你快速记住快捷键.当你用鼠标完成某功能时,它会指示有相应的快捷键来完成刚才的功能,同时指导你为经常重复的操作建立快捷键. SerialVersionUID ...

  10. web程序的路径笔记

    "/"与”\“区别:”/“是unix系统区分文件层级的标志,因为当前web应用程序在服务器端大都使用基于unix系统开发的操作系统,所以web程序包括浏览器里url都遵以”/“来区 ...