What is flow control?
Like other languages, node. JS is an unavoidable difficulty in how code is organized and how to write clean code when it is written.
Also, because of the natural nature of node. JS (asynchronous, event-driven), good code organization is more important.
The so-called flow control refers to the serialized execution of a node. JS Task code organization means.
Like other languages, task flows can be organized into two types (serial, parallel) such as:
How to flow control?
One way is to use the various third-party modules () provided by the node. JS community, and the other way is to write the relevant code ourselves. For the efficiency of engineering development, using third-party libraries is certainly a better choice, but in order to better understand the asynchronous principle of node. js, we try to implement two kinds of flow control.
A Simple demo of serial flow control
The following code implements the ability to output different text every second.
SetTimeout (function () {
Console.log ("first");
SetTimeout (function () {
Console.log ("Sencond");
SetTimeout (function () {
Console.log ("third");
}, 1000);
}, 1000);
}, 1000);
If you use a third-party library to implement serial flow control, the code would be:
var flow = require (' nimble ');
Flow.series ([
Function (callback) {
SetTimeout (function () {
Console.log ("first");
Callback ();
}, 1000)
},
Function (callback) {
SetTimeout (function () {
Console.log ("Second");
Callback ();
}, 1000)
},
Function (callback) {
SetTimeout (function () {
Console.log ("third");
Callback ();
}, 1000)
}
]);
More code and more maintainable. In particular, the advantage of using flow control is obvious when the serial call chain is extremely long.
How do we implement the relevant code ourselves? Here's an example:
var tasks = [
Function (callback) {
SetTimeout (function () {
Console.log ("first");
Next ();
}, 1000)
},
Function (callback) {
SetTimeout (function () {
Console.log ("Second");
Next ();
}, 1000)
},
Function (callback) {
SetTimeout (function () {
Console.log ("third");
Next ();
}, 1000)
}
];
function Next () {
var currenttask = Tasks.shift ();
if (currenttask) {
Currenttask ();
}
}
Next ();
OK, it's simple, let's look at parallelism again.
Parallel Flow Control
The following code assumes that we ran 10 parallel tasks:
var taskcounter = 0;
var tasksum = 10;
function istaskcompleted () {
if (++taskcounter = = tasksum) {
Console.log (' All job done ');
}
}
function Job () {
Lots of code here
Istaskcompleted ();
}
for (var i = 0; i < i++)
Job ();
Use nimble to solve the same problem:
var flow = require (' nimble ');
Flow.parallel ([
Job (),
Job (),
Job (),
Job (),
Job (),
Job (),
Job ()
]);
Summary
This article is a very concise summary of the flow control, the amount of information is not big, we forgive.
node. JS Learning note implementing flow control