Use async to free your brain

Source: Internet
Author: User

In JS, code nesting and code callback are very common. They are not only difficult to write but are not harmful. It is a headache for me to wait for the codoon

function () {    function () {        function () {            function () {                //pass            }        }    }}

This is a conventional nesting. If each function has a lot of logic processing, it will lead to a very long code, which is not only difficult to code, but also very painful to read, this is a good situation in JS, and there are still very bad cases. Consider asynchronous nesting.

var path = './async.txt';// check if async.txt existsfs.stat(path, function (err, stats) {    if (err)        return err    if (stats == undefined) {        fs.readFile(__filename, function (err, content) {            if (err)                return err            var code = content.toString();            fs.writeFile(path, code, function (err) {                if (err)                    return err                console.log('async.txt created!');            });        });    }});

 

This is an asynchronous nested code. First, check whether the file exists. If it does not exist, extract the content of a file and write it into another file. It looks good, however, it is a pity that such writing cannot return errors to the top layer, such as FS. the ERR of writefile return cannot be in FS. received in stat. If you want to receive internal errors from the outer layer, you will see very anti-human Code as follows:

function start (path,filePath){    stats(path,function(err,stat){        if (err)                                   return err;                else if(stat == undefined){            reads(filePath,function(err,data){                if (err)                    return err;                var code = data.toString();                writes(code,function(err,result){                    if (err)                        return err                    console.log('async.txt created!');                })                            })        }    })}function stats (path, fn) {    fs.stat(path, function (err, stats) {        if (err)            fn(err, null);        fn(null, stats);    });}function reads (filePath,fn){    fs.readFile(filePath,function(err,content){        if (err)            fn(err, null);        fn(null, content);    });}function writes(data,fn){    fs.writeFile(filePath,data,function(err,content){        if (err)            fn(err, null);        fn(null, content);    });}

 

WTF, this disgusting code is really undesirable, but you have, if you want to accept error messages in the outer layer before async, the general method is to extract asynchronous code, including callback, into a single method and then call it, this will make the code structure more bloated and more anti-human. I don't want to look at it at a glance! Not only is writing painful, but maintenance more painful

But with async, everything is different.

 

var fs = require('fs');var async = require('async');var path = './async.txt';async.waterfall([    // check if async.txt exists    function(cb) {        fs.stat(path, function(err, stats) {            if (stats == undefined) cb(null);            else console.log('async.txt exists');        });    },    // read the contents of this file    function(cb) {        fs.readFile(__filename, function(err, content) {            var code = content.toString();            cb(null, code);        });    },    // write the content to async.txt    function(code, cb) {        fs.writeFile(path, code, function(err) {            if (err) throw err;            console.log('async.txt created!');        });    }]);

The structure after the change is like writing asynchronous callback code like synchronization. Not only is the structure clear, but the code is very simple. After writing the code, the head will not hurt, and the legs will not be sour. It feels like the time is so good! This is a big killer that frees me from codoon! Of course, the wind. js of Lao Zhao is more suitable. The async and await statements in net 4.5 are very sharp.

Async transfer door https://github.com/caolan/async#waterfall
Wind. js portal http://windjs.org/cn/.

Of course, node. js's well-known async won't only have this function, but the younger brother is not easy to learn. It will only be here. If you have any mistakes, please make a brick.
Enjoy!

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.