Node. js Study Notes 02 Implementing flow control
Like other languages, it is inevitable that Node. js organizes code and writes clean code when writing code. At the same time, due to the natural characteristics of Node. js (asynchronous and event-driven), good code organization is even more important. The so-called flow control refers to the Code organization means for serializing the execution of node. js tasks. Like other languages, task streams can be organized into two types (serial, parallel) How to flow control? One method is to use various third-party modules () provided by the node. js community, and the other is to write relevant code by ourselves. Third-party libraries are certainly a better choice for engineering development efficiency. However, to better understand the asynchronous principles of node. js, we try to implement two types of Stream Control on our own. The code below A simple demo of serial flow control provides the ability to output different texts 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 stream control, the code will be like this: 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 but more maintainable. Especially when the serial call chain is very long, the advantage of using stream control is very obvious. How do we implement the relevant code? The following is 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 easy. Let's look at parallelism. 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 <10; I ++) Job (); Use nimble to solve the same problem: var flow = require ('nimble '); flow. parallel ([Job (), Job ()]);
Summary This article is a concise Summary of flow control, with a small amount of information.