Home  >  Article  >  Web Front-end  >  How to determine whether execution is completed during multiple asynchronous processes in node.js (detailed tutorial)

How to determine whether execution is completed during multiple asynchronous processes in node.js (detailed tutorial)

亚连
亚连Original
2018-06-21 17:17:571545browse

This article mainly introduces to you several solutions for judging whether the execution is completed in multiple asynchronous processes of node.js. The article introduces it in detail through sample code, which has certain reference for everyone's study or work. Value, friends in need come and take a look below.

Preface

This article mainly introduces to you the relevant content about judging whether the execution is completed in multiple asynchronous processes of node.js. It may be like this If you don’t understand it very well, let’s take a look at the detailed introduction.

Scenario:

I want to request a large amount of network data, for example, I want to get 1000 results, but the data processing speed is slow and there is a timeout. The risk can be divided into 10 processing times, with 100 items processed each time; all requests will be processed uniformly after they are completed.

Such an application scenario can be handled as follows:

Option 1: Determine the requested data entry

// 模拟网络请求
function fetch(url, callback) {
 setTimeout(function (){
 callback(null, {
  subjects: [{
   data: Math.round(Math.random() * 100)
  }]
  });
 }, 2000);
}
// 实现方案1
function multiTask_1 () {
 var arr = [];
 var baseUrl = 'https://api.douban.com/v2/movie/top250';
 for (var start = 0; start < 10; start++) {
 var url = baseUrl + &#39;?start=&#39; + start + "&count=1";
  fetch(url, function(error, res) {
  var data = res.subjects;
  arr = arr.concat(data);
  // 调用完成后统一处理
  if (arr.length === 10) {
   console.log(arr);
  }
 });
 }
}

Use arr.length to judge the running result. If arr.length is not what we expect, such as one missing due to network transmission or processing exception, then We will not be able to do subsequent processing. This processing method has strong business coupling; it is not universal.

Option 2: Determine the number of asynchronous process executions

// 方案2
function multiTask_2 () {
 var taskWatcher = 0;
 var arr = [];
 var baseUrl = &#39;https://api.douban.com/v2/movie/top250&#39;;
 for (var start = 0; start < 10; start++) {
 taskWatcher++;
 var url = baseUrl + &#39;?start=&#39; + start + "&count=1";
 fetch(url, function(error, res) {
  var data = res.subjects;
  arr = arr.concat(data);
  taskWatcher--;
  if (taskWatcher === 0) {
   console.log(arr);
  }
 });
 }
}

The judgment conditions of option 2, the tasksWatcher here acts as an observer of the asynchronous task execution, It is only related to the number of calls to the asynchronous procedure and has nothing to do with other processing procedures. Are there any other options?

Option 3: Promise.all()

Promise.all(iterable) The method returns a Promise, which will be resolved after all Promises in the iterable object have been resolved, or rejected after any Promise has been rejected.

function multiTask_3 () {
 // var taskWatcher = 0;
 var taskStack = [];
 var arr = [];
 var baseUrl = &#39;https://api.douban.com/v2/movie/top250&#39;;
 for (var start = 0; start < 10; start++) {
 taskStack.push(
  new Promise((resolve, reject) => {
  var url = baseUrl + &#39;?start=&#39; + start + "&count=1";
  fetch(url, function(error, res) {
   var data = res.subjects;
   arr = arr.concat(data);
   resolve();
  });
  })
 );
 }
 Promise.all(taskStack).then(function () {
 console.log(arr);
 });
}

This method is more versatile. If the asynchronous task types are different, it can also be solved in this way. However, attention should be paid to the handling of reject. Avoid its impact on final processing.

Option 4: EventProxy

EventProxy was written by Pu Ling, https://github.com/JacksonTian/eventproxy

 var ep = new EventProxy();
 var arr = [];
 ep.after(&#39;fetchData&#39;, 10, function (list) {
 list.forEach(function(item){
  arr = arr.concat(item); 
 });
 console.log(arr);
 });
 var baseUrl = &#39;https://api.douban.com/v2/movie/top250&#39;;
 for (var start = 0; start < 10; start++) {
 var url = baseUrl + &#39;?start=&#39; + start + "&count=1";
  fetch(url, function(error, res) {
  var data = res.subjects;
  ep.emit(&#39;fetchData&#39;, data);
 });
 }

EventProxy is based on the event subscription/publishing model. The after method here can listen to multiple events, and the callback stores an array of data results of multiple asynchronous tasks; in addition, EventProxy also supports listening for multiple different events. and processing.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to configure the interface proxy using vue-cli

How to use the form-data format to transfer files in NodeJs

How to implement lazy loading of images in WeChat applet

How to achieve focus image effect using js

The above is the detailed content of How to determine whether execution is completed during multiple asynchronous processes in node.js (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn