Nodejs Async use Method (solve multi-layer callback nesting)

Source: Internet
Author: User

Since Nodejs is processed asynchronously, sometimes we want to synchronize the data out of MySQL, and finally we need to use this extension in processing logic;

This extension avoids multiple levels of callbacks;

Installation method:
NPM Install Async
How to use: 1, parallel multiple functions in parallel execution 

1 varAsync = require (' async ');2 3 Async.Parallel (4     [5         function(callback) {6             //Query Database code here7Daouser.getuserbyid (UserId,function(err, user) {8 callback (err, user);9             });Ten         }, One         function(callback) { A             //Query Database code here -Daouser.gettotal (Callback,function(Err, count) { - callback (Err, count); the             }); -         } -         //If you still need to query the data to continue adding methods -     ], +     function(err, results) { -         varuser = Results[0]; +         varCount = results[1]; A     } at);

2, waterfall several methods to execute sequentially, the return value of the previous function can be passed to the next function

1 varAsync = require (' async ');2 3 Async.waterfall ([4     function(callback) {5Daouser.getuseridbyname (UName,function(Err, userId) {6CallbackNULL, userId);7         });8     },9     function(UserId, callback) {TenDaotask.getdatebyuid (UserId,function(err, tasks) { OneCallbackNULL, tasks); A         }); -     } -],function(err, result) { the     vartasks =result; -});

Nodejs Async use Method (solve multi-layer callback nesting)

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.