Detailed explanation of learning node. js from zero asynchronous control tool async (8)

  • 2021-07-24 09:32:07
  • OfStack

Preface

When you write asynchronous programs, the biggest headache is that you don't know when the results will be returned to us, and then perform the following operations. Most of the time, you can only put the following operations into the functions that return success, or use counters and other methods.

Two typical ones are: the latter operation needs to rely on the result of the last asynchronous operation; Multiple asynchronous operations are executed in parallel, and the next operation is executed after all of them are executed.

Of these two operations, the first asynchronous program may be written as follows:


db.select(SQL1, function(res1){
 db.delete(SQL2, function(res2){
 db.insert(SQL3, function(res3){
 // ...
 })
 })
});

Write the following operations to the callback function after successful execution. The second parallel asynchronous operation can use the counter method. When each asynchronous call is successful, the counter is incremented by 1. When all asynchronous calls are successful, then execute:


var count = 0;
var success = function(){
 count++;
 if(count>=3){ 
  console.log(' Complete execution ...');
 }
}

var select = function(){
 db.select(sql, function(res){
  success();
 })
}
var select2 = function(){
 db.select(sql, function(res){
  success();
 })
}
var select3 = function(){
 db.select(sql, function(res){
  success();
 })
}
select();
select2();
select3();

These writing methods are very troublesome, and the code logic is chaotic, and debugging is also very inconvenient. Then async, a sharp tool for asynchronous control, will be used.

Introduction

The purpose of async is to control the process, and it provides a lot of methods to call.

These methods can be divided into three categories:

Collection class (Collections) Process Control Class (Control Flow) Tools Class (Utils)

Below, we pick out several methods from these three categories to explain.

2. Function introduction

There are many methods available in async, but we will only explain a few representative ones. Others can be found in the official document: http://caolan.github.io/async/docs.html.

2.1 Collection classes

The main methods in the collection class are some, 'map', 'each', 'every', etc. These methods perform callback functions after performing the same operation on arrays or combinations.

Let's take map as an example. map performs the same asynchronous operation on every 1 element in the collection and gets the result. All the results will be summarized into the final callback.
To use, map receives three parameters, which are:

参数名称 类型 说明
coll iteratee callback
Array | Iterable | Object function function
需要处理数组,集合或其他可迭代的类型 迭代方法,用来对集合中的每1项进行处理。该方法接收两个参数(item, callback);item为集合中的每1项, callback为回调函数。callback需要带有err(有时可能为null)和处理后的数据,callback(err, data) 最终回调函数,当集合处理完毕后调用此函数,传递两个参数err和result,result为之前处理后的所有的结果的集合

Note: The intermediate processing function iteratee processes every item in coll concurrently, so there is no guarantee that iteratee will be completed in sequence. However, if coll is an array, the final result set results is arranged in the order in coll; If coll is a collection (Object) type, results will be an array type, and the results will be arranged roughly in the order of the keys of coll (but the difference may change in different JavaScript engines).

Let's take an example and use map to get the contents of several files:


var files = ['./file/cnode_1.txt', './file/cnode_2.txt', './file/cnode_3.txt'];

//  Read the contents of a file 
//  No. 1 1 Parameters   An array of file name lists 
//  No. 1 2 Parameters   Pass in every 1 Items and callback functions 
//  No. 1 3 Parameters  results Is a collection of all results 
async.map(files, function(file, cb){
 fs.readFile(file, 'utf-8', function(err, data){
  cb(err, data);
 })
}, function(err, results){
 console.log( results );
})

Moreover, if the middle processing function is relatively large and you don't want to write it in map, you can also write it as a function and pass it in, but the parameter passing still needs to conform to the rules:


var files = ['./file/cnode_1.txt', './file/cnode_2.txt', './file/cnode_3.txt'];

var read = function(file, cb){
 fs.readFile(file, 'utf-8', function(err, data){
  cb(err, data);
 })
}
async.map(files, read, function(err, result){
 console.log( result );
})

There is also an mapLimit, which can pass a parameter limit to limit the amount of concurrency: mapLimit(coll, limit, iteratee, callbackopt) :


//  The number of concurrency is 2
async.mapLimit(files, 2, read, function(err, result){
 console.log( result );
})

At the same time, there are other methods in the collection class, so let's also know a little bit:

each: Similar to map, but there is no results in the final callback function, and each only loops and does not handle the result every: The parameters (err, boolean) of the intermediate processing function iteratee need to pass an boolean value. If the result of all options is true, results is true some: Similar to every, except that results is true as long as the result of one of the options is true filter: The coll is screened and the result is true reject: Contrary to filter, the result of screening is false concat: Merge the results of each asynchronous operation into an array

2.2 Process Control Class

The above collection class performs the same processing on 1 collection, and after each item in the collection is processed, the result is callback processed. When multiple callback methods are executed, these callback methods need to be controlled.

When multiple callback methods are executed, there are usually several processes:

Serial and unrelated, that is, after one is executed, the next one is executed in turn, and there is no data interaction between them. After all are executed, the last callback function is executed. You can use the async.series Serial and related, that is, after executing one, the next one will be executed in turn, and the result of the last callback function will be used as the parameter of the next callback function. You can use async. waterfall Parallel, these several callback functions are executed concurrently at the same time, and the last callback function is executed after all of them are executed. You can use the async.parallel

Of course, there are other more complicated processes, and only the above three situations are discussed here.


async.series , async.waterfall And async.parallel The grammar of is 1 Like: 
async.Method(coll, function(err, results){

})

Where coll can be either an array or an json format, and the type of results corresponds to coll.

Serial and uncorrelated async.series :


//  Serial and unassociated, array format 
async.series([
 function(cb){
  getAllList(function(result){
   cb(null, result);
  });
 },
 function(cb){
  getAllUser(function(result){
   cb(null, result);
  });
 }
], function(err, result){
 console.log(result);
})

Simultaneous serial asynchronism can be in json format:


//  Serial and uncorrelated, json Number 
async.series({
 one: function(cb){
  getAllList(function(result){
   cb(null, result);
  });
 },
 two: function(cb){
  getAllUser(function(result){
   cb(null, result);
  });
 }
}, function(err, result){
 console.log(result);
})

Serial and associated async.waterfall :


//  Serial and up 1 The results are as follows 1 Parameters of 
async.waterfall([
 function(cb){
  getListById(1, function(result){
   cb(null, result);
  });
 },
 function(params, cb){
  console.log(params);
  getAllUser(function(result){
   cb(null, result);
  });
 }
], function(err, result){
 console.log(result);
})

Parallel async.parallel :


//  Parallel, getAllList And getAllUser Simultaneous execution 
async.parallel([
 function(cb){
  getAllList(function(result){
   cb(null, result);
  });
 },
 function(cb){
  getAllUser(function(result){
   cb(null, result);
  });
 }
], function(err, result){
 console.log(result);
})

For parallel asynchronous operations, here is another async.parallelLimit Limit the number of concurrency:


var count = 0;
var success = function(){
 count++;
 if(count>=3){ 
  console.log(' Complete execution ...');
 }
}

var select = function(){
 db.select(sql, function(res){
  success();
 })
}
var select2 = function(){
 db.select(sql, function(res){
  success();
 })
}
var select3 = function(){
 db.select(sql, function(res){
  success();
 })
}
select();
select2();
select3();
0

2.3 Tool classes

async also provides many tool methods for use. For example, async. log can output the value in the callback method. The first parameter is the function, and the following parameters are the parameters passed to the function:


var count = 0;
var success = function(){
 count++;
 if(count>=3){ 
  console.log(' Complete execution ...');
 }
}

var select = function(){
 db.select(sql, function(res){
  success();
 })
}
var select2 = function(){
 db.select(sql, function(res){
  success();
 })
}
var select3 = function(){
 db.select(sql, function(res){
  success();
 })
}
select();
select2();
select3();
1

There are also apply, dir, timeout and other methods.

Summarize


Related articles: