Nodejs Async Calling Async

Source: Internet
Author: User

Hesitation Nodejs is an asynchronous programming model, and some things that are easy to do in synchronous programming are now cumbersome, and Async's process control is to simplify these operations
var async = require (' async ');

1. Series (multiple functions are executed once, there is no data exchange between them)
Series (Tasks,[callback]) sequentially executes the function in the array, in the set, and immediately executes the next function when the previous function finishes executing, and if the function triggers an error, it can be verified in the callback function, otherwise it will be executed until the tasks are completed
There are multiple asynchronous functions that need to be called sequentially, one completes before the next, no data is exchanged between functions, and the series can be used only if the order of execution is guaranteed.
Tasks are passed an array function
Const Async=require (' async ');
Async.series ([
Function (callback) {
Console.log ("one");
Callback (NULL, "one");
},
Function (callback) {
Console.log ("both");
Callback (NULL, "both");
}
],function (err,results) {
Console.log ("err======" +err);
Console.log ("results======" +results);
Console.log ("typeof results======" +typeof (results));
})

Output after running:

One
Both
Err======null
Results======one,two
typeof Results======object

 I think it's important here that err is the error message for the above two functions, and results This parameter is an array object whose values are the parameters of each callback inside the array function 
above the code:
1, execute each function in a function array sequentially , each function execution completes before the next function can be executed.
2, if any function passes an error to its callback function, the subsequent function is not executed, and the error and the result of the function already executed will be passed to the last callback
3 in the series immediately. When all functions have been executed (without error), the result of passing each function to its callback function is merged into an array, passed to the last callback of the series.
4. You can also provide tasks in the form of JSON. Each property is executed as a function, and the result is passed to the last callback of the series in JSON form, which is more readable.
5, if there is an error in one of the functions, how the series function handles: There is a function error in the middle. The function after the error is not executed, and the result of the function that was previously executed correctly is passed to the final callback.
6, if the value of a function passed to the callback is undefined,null,{},[], and so on, the series How to handle: If the data passed by a function is undefined, null, {}, [] and so on, they will be passed to the final callback.
7, it is also important to note that multiple series calls are not sequential, because the series itself is an asynchronous call.
How do I get an error in simulating multiple functions in a series
Const Async=require (' async ');
Async.series ([
Function (callback) {
Console.log ("one");
Callback ("Error", "one");
},
Function (callback) {
Console.log ("both");
Callback (NULL, "both");
}
],function (err,results) {
Console.log ("err======" +err);
Console.log ("results======" +results);
Console.log ("typeof results======" +typeof (results));
})
Post-run output:

One
Err======error
Results======one
typeof Results======object

Send JSON form tasks

Code:

Const Async=require ("async");

Async.series ({
One:function (callback) {
SetTimeout (function () {
Callback (null,1);
},200)
},
Two:function (callback) {
SetTimeout (function () {
Callback (null,2);
})
}
},function (err,results) {
Console.log ("results0=====" +results[' one ');
Console.log ("results1=====" +results[')];
})
Post-run output:

Results0=====1
results1=====2

This is a JSON-formatted results

2, parallel

Parallel (Tasks,[callback]) executes the methods in the array collection in parallel without having to wait until the previous function finishes executing the next function, and if the function has made an error, you can verify the callback function again

Executes multiple functions in parallel, each of which executes immediately, without waiting for other functions to execute first. The data in the array passed to the final callback is in the order declared in the tasks, rather than in the order in which the completion is performed.
  

If a function fails, the result value of err and the function that has been executed is immediately passed to parallel final callback. The values of other functions that are not executed are not propagated to the final data, but are taken up in a position.

While supporting the tasks in JSON form, the final callback result is also in JSON form.


Const Async=require (' async ');

Async.Parallel ([
Function (callback) {
SetTimeout (function () {
Callback (NULL, "one");
},200)
},
Function (callback) {
SetTimeout (function () {
Callback (NULL, "both");
},100);
}
],
function (err,results) {
Console.log ("err=====" +err);
Console.log ("results=====" +results);
})
Post-run output:

Err=====null
Results=====one,two

Code:

Const Async=require (' async ');

Async.Parallel ([
Function (callback) {
SetTimeout (function () {
Callback (NULL, "one");
},400)
},
Function (callback) {
SetTimeout (function () {
Callback ("Err", "both");
},200);
},
Function (callback) {
SetTimeout (function () {
Callback (NULL, "three");
},100);
}
],
function (err,results) {
Console.log ("err=====" +err);
Console.log ("results=====" +results);
})
Post-run output:

Err=====err
Results=====,two,three

Code:

Const Async=require (' async ');

Async.Parallel ({
One:function (callback) {
SetTimeout (function () {
Callback (NULL, "one");
},400)
},
Two:function (callback) {
SetTimeout (function () {
Callback (NULL, "both");
},200);
},
Three:function (callback) {
SetTimeout (function () {
Callback (NULL, "three");
},100);
}
},
function (err,results) {
Console.log ("err=====" +err);
Console.log ("results=====" +results[' one ');
Console.log ("results=====" +results[')];
Console.log ("results=====" +results[' three ');
})
Post-run output:

Err=====null
Results=====one
Results=====two
Results=====three

3, Waterfall

Waterfall (tasks,callback), multiple functions are executed sequentially, and the previous output is the input of Roar one,

Similar to series, the functions are executed sequentially, but the value generated by each function is passed to the next function, and if there is an error in the middle, the subsequent function will not be executed. The error message and the resulting results will be passed to Waterfall's final callback, which does not support JSON-formatted tasks.

* Note that all callback must be shaped like callback (err, result), but the Err parameter does not need to be declared in the preceding functions, it is automatically processed.

There is an error in the middle of the function, and the err and the resulting value will be passed directly to the final callback, and the subsequent function no longer executes

Code:

Const Async=require (' async ');
Async.waterfall ([
Function (callback) {
Callback (NULL, ' One ', ' both ');
},function (Args,arg2,callback) {
Callback (NULL, ' three ');
},function (Arg1,callback) {
Callback (NULL, ' done ');
}
],function (err,results) {
Console.log ("results=====" +results);
})
Post-run output:
Results=====done
Code:
Const Async=require (' async ');
Async.waterfall ([
Function (callback) {
Callback (NULL, ' One ', ' both ');
},function (Args,arg2,callback) {
Callback ("Err", ' three ');
},function (Arg1,callback) {
Callback (NULL, ' done ');
}
],function (err,results) {
Console.log ("results=====" +results);
})
Post-run output:

Results=====three

4, whilst

Whilst (Test,fn,callback), which can be used for asynchronous calls while, the first parameter is the validation condition, the second argument is the execution function, and the third parameter is the callback function after the validation failure, generally more in the delay animation

is equivalent to while, but the asynchronous call in it will wake up the next loop after completion.

Code:

Const Async=require (' async ');
var count=0;
Async.whilst (
function () { //validation continued successfully, failed callback
Return count<5;
},
Function (callback) { ///1 seconds in the past the callback execution is complete, then loop, know Count=5 time, the first method, error, go to the third method
Console.log ("Count" +count);
count++;
SetTimeout (callback,1000);
},
function (Err) {
Console.log ("err" +err);
}
)
Output after code runs:

Count0
Count1
Count2
Count3
Count4
Errnull

The function is simple, the condition variables are usually defined outside, available for each function to access, in the loop, the value generated by the asynchronous invocation is actually discarded, because the last callback can only pass in the error message.

In addition, the second function FN needs to be able to accept a function CB, the CD must eventually be executed to indicate an error or a normal end

Error Midway. Call the third function immediately after an error.

Code:

Const Async=require (' async ');
var count=0;
Async.whilst (
function () { //validation continued successfully, failed callback
Return count<5;
},
Function (callback) { //5 seconds past
Console.log ("Count" +count);
count++;
if (count===1) {
Callback ("Err");
}else{
SetTimeout (callback,1000);
}
},
function (Err) {
Console.log ("err" +err);
}
)
Post-run output:

Count0
Errerr

The second function is ignored even if it produces a value. The third function can only get an err.





Nodejs Async Calling 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.