node.js-Serialization Process Control

Source: Internet
Author: User

Main Source: Wuhaishing translation, "node. js combat."

Serial tasks: A task that needs to be followed by a sitting is called a serial task.

You can use callbacks to make several asynchronous tasks execute sequentially, but if you have too many tasks, you have to organize them, otherwise too much callback nesting can mess up the code.

In order to have several asynchronous tasks executed sequentially with serialization process control, these tasks need to be placed in an array in the desired order of execution, which will serve as a queue: After completing a task, remove the next one from the array sequentially.

Each task in the array is a function. After the task is completed, a handler function should be called to tell it the error state and result.

To demonstrate how to implement serialization process control, we are going to make a small program that gets the title and URL of an article from a randomly selected RSS feed and displays it.

To download two auxiliary modules from NPM storage, enter the following command at the command line (for example, Mac System):

mkdirinstallinstall htmlparser

The request module is a simplified HTTP client that can obtain RSS data. The Htmlparser module can convert raw RSS data into JavaScript structure.

Create a random_story.js file under the new directory that contains the following code:

varFS = require (' FS ');varRequest = require (' request '));varHtmlparser = require (' Htmlparser '));varConfigfilename = './rss_feeds.txt ';//ensure that the file containing the RSS subscription list existsfunctionCheckforrssfile () {fs.exists (Configfilename,function(exists) {if(!exists) {            returnNextNewError (' Missing RSS file: ' +configfilename)); } Next (NULL, Configfilename); });}//Read and parse a file containing an RSS subscription listfunctionReadrssfile (configfilename) {fs.readfile (Configfilename,function(Err, feedlist) {if(err) {returnNext (ERR); } feedlist= Feedlist.tostring (). Replace (/^\s+|\s+$/g, "). Split (" \ n ")); varRandom = Math.floor (Math.random () *feedlist.length); Next (NULL, Feedlist[random]); });}//send an HTTP request to the intended source for datafunctionDownloadrssfeed (Feedurl) {request ({Uri:feedurl},function(err, res, body) {if(err) {returnNext (ERR); }        if(Res.statuscode!== 200) {            returnNextNewError (' Abnormal response status code ')); } Next (NULL, body); });}//resolves to an array of entriesfunctionParserssfeed (RSS) {varHandler =NewHtmlparser.    RssHandler (); varParser =NewHtmlparser.    Parser (handler);    Parser.parsecomplete (RSS); if(!handler.dom.items.length) {returnNextNewError (' No RSS items found. '))); }    varitem =Handler.dom.items.shift ();    Console.log (Item.title); Console.log (Item.link);}vartasks =[Checkforrssfile, Readrssfile, Downloadrssfeed, parserssfeed];functionNext (err, result) {if(err) {Throwerr; }    varCurrenttask =Tasks.shift (); if(currenttask) {currenttask (result); }}//start a serialization taskNext ();

Before you try this program, create a rss_feeds.txt file in the same directory as the program script. This contains only a predetermined source information:

http://dave.smallpict.com/rss.xml

Then execute the script:

Node Random_story.js

Returns information such as. Successful implementation of a serialization process control.

[Serialization Process Control in async/await form]

Then the source code was rewritten, and changed into the async/await form of ES7. The level is limited, if there are errors please point out!

Let FS = require (' FS '); let request= Require (' request ')); let Htmlparser= Require (' Htmlparser '); let Configfilename= './rss_feeds.txt ';functionCheckforrssfile () {return NewPromise (Resolve, reject) ={fs.exists (Configfilename, (exists)= {            if(!exists) {Reject (NewError (' Missing RSS file: ' +configfilename));        } resolve ();    }); });}functionReadrssfile (configfilename) {return NewPromise (Resolve, reject) ={fs.readfile (Configfilename, (err, feedlist)= {            if(Err) {reject (err); } feedlist= Feedlist.tostring (). Replace (/^\s+|\s+$/g, "). Split (" \ n ")); Let Random= Math.floor (Math.random () *feedlist.length);        Resolve (Feedlist[random]);    }); });}functionDownloadrssfeed (feedurl) {return NewPromise (Resolve, reject) ={request ({Uri:feedurl}, (err, res, body)= {            if(Err) {reject (err); }            if(Res.statuscode!== 200) {Reject (NewError (' Abnormal response status code '));        } resolve (body);    }); });}functionParserssfeed (RSS) {Let handler=NewHtmlparser.    RssHandler (); Let parser=NewHtmlparser.    Parser (handler);    Parser.parsecomplete (RSS); if(!handler.dom.items.length) {Throw NewError (' No RSS items found. ')); } Let Item=Handler.dom.items.shift ();    Console.log (Item.title); Console.log (Item.link);} AsyncfunctionGetrssfeed () {await checkforrssfile (); Let URL=await Readrssfile (configfilename); Let RSS=await downloadrssfeed (URL); returnRSS;} Getrssfeed (). Then (RSS= Parserssfeed (RSS), E = Console.log (e));

node.js-Serialization Process Control

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.