Christmas Trees, promises and event emitters

Source: Internet
Author: User
Tags emit

Today, a colleague asked me what the following code means:

var function () {  events. Eventemitter.call (this//  What does this line mean?) // and this line?  

I didn't quite understand it, so I studied it a bit. Here are some of my experiences.

Christmas Trees and Errors

If you write JavaScript or Nodejs code, you may experience callback hell. Each time you make an asynchronous call, according to callback's contract, you need to pass a function as the callback function, and the first parameter of the function defaults to the error received. This is a great deal, but there are still two minor problems:

1. There is a need to check for error in each callback process-it's annoying.

2. Each callback causes the code to be indented to the right, and if there are many levels of callbacks, our code looks like a Christmas tree:

In addition, if each callback is an anonymous function and contains a lot of code, maintaining such code can be maddening.

What would you do?

There are many ways to solve these problems, and below I will provide three different ways to write the code to illustrate the difference between them.

1. Standard callback function

  2. Event Emitter

  3. Promises

I created a simple class "User registration" to save the email to the database and send it. In each example, I assume that the save operation was successful and that the send email operation failed.

1) Standard callback function

As mentioned earlier, Nodejs has a convention on the callback function, which is the error before the callback. In each callback, if an error occurs, you need to throw the error and truncate the rest of the callback operation.

########################### registration.js #################################varRegistration =function () {  if(! ( This instanceofRegistration))return Newregistration (); var_save =function(email, callback) {SetTimeout (function() {Callback (NULL); }, 20);  }; var_send =function(email, callback) {SetTimeout (function() {Callback (NewError ("Failed to send")); }, 20);  };  This. Register =function(email, callback) {_save (email,function(err) {if(ERR)returncallback (ERR); _send (email,function(Err) {callback (ERR);    });  }); };}; Module.exports=registration;########################### app.js #################################varRegistration = require ('./registration.js '));varRegistry =Newregistration (); Registry.register ("[Email protected]",function(Err) {Console.log ("Done", err);});

Most of the time I prefer to use standard callback functions. If you think your code structure looks very clear, then I don't think "Christmas Tree" will cause me too much trouble. Error checking in callbacks can be a bit annoying, but the code looks simple.

2) Event Emitter

In Nodejs, there is a built-in library called Eventemitter very good, it is widely used in Nodejs's entire system.

You can create an instance of emitter, but it is more common to inherit from emitter so that you can subscribe to events generated from specific objects.

The key thing is that we can connect events into a workflow such as "send email as soon as it is successfully saved".

Additionally, an event named error has a special behavior that, when the error event is not subscribed to by any object, it prints the stack trace information in the console and exits the entire process. In other words, an unhandled errors will cause the entire program to collapse.

########################### registration.js #################################varUtil = require (' util '));varEventemitter = require (' Events '). Eventemitter;varRegistration =function () {  //Call the base constructorEventemitter.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 ',NewError ("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 Eventemitterutil.inherits (registration, eventemitter); Module.exports=registration;########################### app.js #################################varRegistration = require ('./registration.js '));varRegistry =Newregistration ();//if we didn ' t register for ' error ' and then the program would close when an error happenedRegistry.on (' Error ',function(Err) {Console.log ("Failed with Error:", err);});//Register for the success eventRegistry.on (' Success ',function() {Console.log ("Success!");});//Begin the RegistrationRegistry.register ("[email protected]");

You can see that there is very little nesting in the code above, and we don't have to check the errors in the callback function as we did before. If an error occurs, the program throws an error message and bypasses the rest of the registration process.

3) Promises

Here are a lot of notes about promises, such as Promises-spec, Common-js and so on. Here's what I understand.

Promises is a convention that makes management of nested callbacks and errors look more elegant. For example, to invoke a Save method asynchronously, we do not have to pass a callback function to it, and the method returns a Promise object. This object contains a then method, and we pass the callback function to it to complete the registration of the callback function.

As far as I know, people tend to write code in the form of standard callback functions, and then use libraries authoring such as deferred to convert these callback functions into promise form. That's what I'm here to do.

######################### app.js ############################varRegistration = require ('./registration.js '));varRegistry =Newregistration (); Registry.register ("[Email protected]"). Then (function() {Console.log ("Success!"); },    function(Err) {Console.log ("Failed with Error:", err); }); ######################### registration.js ############################varDeferred = require (' deferred '));varRegistration =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 (NewError ("Failed to send"));  });  This. Register =function(email, callback) {//chain promises together and return a promise    return_save (email). then (_send); };}; Module.exports= registration;

Promise eliminates nested calls in code and passes error like Eventemitter. Here I have listed some of the differences between them:

Eventemitter
    • You need to refer to the Util and events libraries, which are already included in the Nodejs
    • You need to inherit your class from Eventemitter.
    • Throws a run-time exception if error is not handled
    • Support for publish/Subscribe mode
Promise
    • To make the entire callback a chain-shaped structure
    • Requires support from the library to convert the callback function into a promise form, such as deferred or Q
    • Will bring more overhead, so it may be a little bit slow
    • Publish/Subscribe mode not supported

Original address: Http://www.joshwright.com/tips/javascript-christmas-trees-promises-and-event-emitters

Christmas Trees, promises and event emitters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.