The practice of node. JS under When.js (promises/a)

Source: Internet
Author: User

Suppose a business scenario:

RSS addresses are available for RSS feeds and stored in files, and RSS addresses are stored in a file.

The business of completing this scenario requires 3 tasks to complete:

1. Read the RSS address from the file.

2. Get RSS.

3. Save in file.

Finally, the three tasks are consolidated.

Get ready:

The file that holds the RSS address, Address.txt.

http://programmer.csdn.net/rss_programmer.html

Task 1:

Reads the contents of the RSS address file and returns it via callback.

var function (Path, callback) {  function  (err, data) {    callback (err, data);  });

Task 2:

Get to RSS via RSS address, and return errors or data via callback.

var  getrss = function   (URL, callback) { var   data = ' function   (Chrunk) {data  +    = Chrunk;    }); Res.on ( ' End ', function   () {callback (    Span>null  , data);  }); }). On ( ' error ', function   (err) {callback (Err,  null   ); });}

Task 3:

Save RSS to file and return an error via callback.

var function (data, callback) {  fs.writefile (function(err) {    callback (ERR);  });

Integration:

 getrssaddress (' Address.txt ',  function   if   (Err) {Console.log (err);   return  ; } getrss (data,  function   (err, data) {
      if   (Err) {Console.log (err);     return  ; } saverss (data,  function   (err) { Span style= "color: #0000ff;"    >if   (ERR) Console.log (err);  }); });});

The above code is full asynchronous processing, using the most common callback to handle the return of asynchronous logic, the benefits are standard notation, everyone can easily accept; The disadvantage is that the coupling is too strong, the handling is very troublesome, the code is not intuitive, especially to deal with the complexity of business logic and the processing of many tasks of the scene, Layers of callback can make people saw stars and code difficult to maintain.

One of the implementations of the PROMISE/A specification is when.js for such a problem domain.

Let's take a look at the transformed code.

Task 1:

 var  getrssaddress = function   var  deferred =   When.defer ()      ; Fs.readfile (path, {encoding:  ' UTF8 '}, function   (err, data) { if   (ERR) deferred.reject (err);       deferred.resolve (data);     });  return  < Span style= "Background-color: #99cc00;" > deferred.promise; }   

Task 2:

varGetrss =function(URL) { var deferred = when.defer (); vardata = '; Http.get (URL,function(res) {Res.on (' Data ',function(chrunk) {data+=Chrunk;      }); Res.on (' End ',function() { deferred.resolve (data);    }); }). On (' Error ',function(Err) { deferred.reject (err);    }); return deferred.promise;}

Task 3:

var function (data) {  var deferred =   when.defer ();  Fs.writefile (function(err) {    ifdeferred.reject (err);    deferred.resolve ();  });   return  deferred.promise;}

Integration:

Getrssaddress (' address.txt ')  . Then (GETRSS). Then (  saverss)   . Catch (function(err) {    console.log (err);  });

Explain:

The "deferred/promise" model defined by the PROMISE/A specification is the "Publish/subscribe" model, which publishes events through Deferred objects, either to complete resolve events or to fail reject events ; a subscription that corresponds to completion or failure through the Promise object.

In the PROMISES/A specification, there are three states for each task: default (Pending), complete (fulfilled), failure (rejected).

1. The default state can be transferred one-way to the completion state, the process is called resolve, the corresponding method is Deferred.resolve (Promiseorvalue);

2. The default state can also be transferred one-way to the failed state, the process is called reject, the corresponding method is deferred.reject (reason);

3. In the default state, task execution information can also be declared through Deferred.notify (update), such as execution progress;

4. The transfer of state is one-time, once the task is changed from the initial pending to other States, it will go into the execution of the next task.

Follow the code above.

Defines a deferred object through When.defer.

var deferred = When.defer ();

After the asynchronous data gets successful, publish a completion event.

Deferred.resolve (data);

After the asynchronous data acquisition fails, a failure event is published.

Deferred.reject (ERR);

and returns the Promise object used as a subscription.

return deferred.promise;

A subscription is a completion/failure/notification subscription through the then method of the Promise object.

Getrssaddress (' address.txt ')  . Then (GETRSS)

Then there are three parameters, namely onfulfilled, onrejected, onprogress

Promise.then (onfulfilled, onrejected, OnProgress)

The last task is resolve (data), the onfulfilled function is triggered, and data is used as its parameter.

The previous task was reject (reason), then onrejected will be triggered and received reason.

At any time, only one of the onfulfilled and onrejected can be triggered and triggered only once.

For handling exceptions, When.js also provides an extremely convenient way to pass errors, and when multiple tasks are executed serially, we can define onrejected only at the last then. You can also call the Catch function after the last then to capture the exception of any one task.

So simple and clear.

Getrssaddress (' address.txt ')  . Then (GETRSS). Then (  saverss)    .  catch(function(err) {    console.log (err);  }); 

Promise is a great convenience for asynchronous programming, allowing us to focus on the implementation of a single task without falling into the pyramid doom, the above code is just basic use, When.js provides more than this article mentioned, the specific reference to the official API.

The practice of node. JS under When.js (promises/a)

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.