Nodejs callback Hell Solution promise Async

Source: Internet
Author: User
Tags readfile

Nodejs ruin the hell is always criticized, the following summarizes some ways to solve the destruction of hell. (Temporary study of relatively shallow)

1.promise

Promise mode is in one of the following three states at any time: incomplete (unfulfilled), completed (resolved), and rejected (rejected). Taking the Commonjs promise/a standard as an example, the then method on the Promise object is responsible for adding handler functions for the completed and rejected states. The then method returns another promise object to facilitate the formation of the Promise pipeline, which returns promise objects in a way that enables the developer to concatenate asynchronous operations, such as then (Resolvedhandler, Rejectedhandler);. The Resolvedhandler callback function fires when the Promise object enters the completion state and passes the result; the Rejectedhandler function is invoked in the deny state. (where Rejectedhandler is optional).

Here's a few nested functions that look more disgusting. (If you change the indent by four characters, imagine)

' Use strict '; Const MD= Require (' markdown-it ') (); Const FS= Require (' FS '); Fs.watchfile (' Nodejs.md ', (curr, prev) ={Let mdstr= Fs.readfile ('./nodejs.md ', ' utf-8 ', (err, data) = ={Let Mddata=Md.render (data); Let Htmltemplate= Fs.readfile ('./index.html ', ' utf-8 ', (err, data) = ={Let HTML= Data.replace (' {content}} ', Mddata);      Console.log (Mddata); Fs.writefile ('./nodejs.html ', HTML, ' Utf-8 ', (err, data) = = {        if(err) {Throwerr; } Else{Console.log (' OK ');    }      });  }); });});

Use promise to achieve the same effect, first encapsulate the asynchronous function, and then the following can be called. It may seem that the code is more than the previous version, but the encapsulated async function can be reused. When the task is more, it doesn't seem like much code. (But look at the last part of the call function is not elegant a lot)

' Use strict '; Const FS= Require (' FS '); Const MD= Require (' markdown-it ')();varQ = require (' q '));functionfs_readfile (file, encoding) {varDeferred =Q.defer (); Fs.readfile (file, encoding,function(err, data) {if(err) Deferred.reject (err);//rejects the promise with ' er ' as the reason    Elsedeferred.resolve (data)//fulfills the promise with ' data ' as the value  }); returnDeferred.promise;//The promise is returned}functionfs_writefile (file, data, encoding) {varDeferred =Q.defer (); Fs.writefile (file, data, encoding,function(err, data) {if(err) Deferred.reject (err);//rejects the promise with ' er ' as the reason    ElseDeferred.resolve (data);//fulfills the promise with ' data ' as the value  }); returnDeferred.promise;//The promise is returned    //return 1;//The Promise is returned}functionfs_watchfile (file, Curr, prev) {varDeferred =Q.defer (); Fs.watchfile (file,function(Curr, prev) {if(!prev) Deferred.reject (err);//rejects the promise with ' er ' as the reason    ElseDeferred.resolve (Curr);//fulfills the promise with ' data ' as the value  }); returnDeferred.promise//The promise is returned}functionMarkdowm_convert (file, encoding, mddata) {varConvertdata =Md.render (Mddata);  Console.log (Convertdata); varDeferred =Q.defer (); Fs.readfile (file, encoding,function(err, data) {if(err) Deferred.reject (err);//rejects the promise with ' er ' as the reason    Else{Data= Data.replace (' {content}} ', Convertdata); Deferred.resolve (data); //fulfills the promise with ' data ' as the value    }  })  returnDeferred.promise;//The promise is returned}//===============promise Implementation =====================Fs_watchfile (' nodejs.md '). Then (function() {    returnFs_readfile ('./nodejs.md ', ' utf-8 '); }). Then (function(mddata) {returnMarkdowm_convert ('./index.html ', ' utf-8 ', Mddata); }). Then (function(data) {Fs_writefile ('./nodejs.html ', data, ' Utf-8 '); });

2.async

Node's async package has a number of countless methods I've only been experimenting with a waterfall for the time being.

Waterfall Waterfall The meaning of the stream and the other function series in Async are almost always executed sequentially, but the difference is that waterfall each execution of a function produces a value and then uses that value for the next function.

The following is a nested two-level read-write file program

Fs.readfile (' 01.txt ', ' utf-8 ',function(err,date) {  fs.writefile (' 02.txt ', date, ' Utf-8 ',  function(err,date) {    console.log (' copy finished ');  })

Use Async.waterfall after the code is as follows

Async.waterfall ([  function(CB) {    fs.readfile (' 01.txt ', ' utf-8 ',function  (err,result) {      cb (Err,result);    });  },function(RESULT,CB) {    Fs.writefile (' 02.txt ', result, ' utf-8 ',function(err,result) {      cb (Err,result);    });  ],function(err,result) {console.log (' copy finished ');})

Nodejs callback Hell Solution promise Async

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.