1. Introduction This article describes the solutions for asynchronous functions, serial execution, and parallel execution in 2. es5 method Before es6 came out, the 3. Asynchronous function serial executionvar items = [ 1, 2, 3, 4, 5, 6 ]; var results = []; function async(arg, callback) { console.log('Parameter is ' + arg +', return result after 1 second'); setTimeout(function () { callback(arg * 2); }, 1000); } function final(value) { console.log('Completed: ', value); } function series(item) { if(item) { async(item, function(result) { results.push(result); return series(items.shift()); // recursively execute all data }); } else { return final(results[results.length - 1]); } } series(items.shift()); 4. Parallel execution of asynchronous functions The above functions are executed one by one, and the next one is executed after the previous one is finished, which is similar to async and await in We can write: var items = [ 1, 2, 3, 4, 5, 6 ]; var results = []; function async(arg, callback) { console.log('Parameter is ' + arg +', return result after 1 second'); setTimeout(function () { callback(arg * 2); }, 1000); } function final(value) { console.log('Completed: ', value); } items.forEach(function(item) {// loop complete async(item, function(result){ results.push(result); if(results.length === items.length) {// Determine whether the number of completed functions is equal to the number of functions to be executed final(results[results.length - 1]); } }) }); 5. Combination of serial and parallel execution of asynchronous functionsIf many asynchronous data (hundreds of them) are executed in parallel, and each asynchronous data contains a lot of (https) request data, it is bound to cause insufficient TCP connections or accumulation of countless call stacks leading to memory overflow. Therefore, it is not easy to execute too much data in parallel, so a combination of parallel and serial methods emerged. The code can be written as follows: var items = [ 1, 2, 3, 4, 5, 6 ]; var results = []; var running = 0; var limit = 2; function async(arg, callback) { console.log('Parameter is ' + arg +', return result after 1 second'); setTimeout(function () { callback(arg * 2); }, 1000); } function final(value) { console.log('Completed: ', value); } function launcher() { while(running < limit && items.length > 0) { var item = items.shift(); async(item, function(result) { results.push(result); running--; if (items.length > 0) { launcher(); } else if(running == 0) { final(results); } }); running++; } } launcher(); 6. es6 method tiny-async-pool, es6-promise-pool, p-limit Simple encapsulation of a function PromiseLimit(funcArray, limit = 5) { // Execute 5 data concurrently let i = 0; const result = []; const executing = []; const queue = function() { if (i === funcArray.length) return Promise.all(executing); const p = funcArray[i++](); result.push(p); const e = p.then(() => executing.splice(executing.indexOf(e), 1)); executing.push(e); if (executing.length >= limit) { return Promise.race(executing).then( () => queue(), e => Promise.reject(e) ); } return Promise.resolve().then(() => queue()); }; return queue().then(() => Promise.all(result)); } use: // Test code const result = []; for (let index = 0; index < 10; index++) { result.push(function() { return new Promise((resolve, reject) => { console.log("start" + index, new Date().toLocaleString()); setTimeout(() => { resolve(index); console.log("End" + index, new Date().toLocaleString()); }, parseInt(Math.random() * 10000)); }); }); } PromiseLimit(result).then(data => { console.log(data); }); Modify the test code and add random failure logic // Modify the test code to fail or succeed randomly const result = []; for (let index = 0; index < 10; index++) { result.push(function() { return new Promise((resolve, reject) => { console.log("start" + index, new Date().toLocaleString()); setTimeout(() => { if (Math.random() > 0.5) { resolve(index); } else { reject(index); } console.log("End" + index, new Date().toLocaleString()); }, parseInt(Math.random() * 1000)); }); }); } PromiseLimit(result).then( data => { console.log("success", data); }, data => { console.log("failed", data); } ); 7. async and await combined with promise allasync function PromiseAll(promises,batchSize=10) { const result = []; while(promises.length > 0) { const data = await Promise.all(promises.splice(0,batchSize)); result.push(...data); } return result; } There are two problems with this writing:
The improvements are as follows: async function asyncPool(array,poolLimit,iteratorFn) { const ret = []; const executing = []; for (const item of array) { const p = Promise.resolve().then(() => iteratorFn(item, array)); ret.push(p); if (poolLimit <= array.length) { const e = p.then(() => executing.splice(executing.indexOf(e), 1)); executing.push(e); if (executing.length >= poolLimit) { await Promise.race(executing); } } } return Promise.all(ret); } use: const timeout = i => new Promise(resolve => setTimeout(() => resolve(i), i)); return asyncPool( [1000, 5000, 3000, 2000], 2,timeout).then(results => { ... }); This is the end of this article about serial and parallel operations in JavaScript asynchronous operations. For more relevant content about serial and parallel operations in JavaScript asynchronous operations, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: HTML css js implements Tab page sample code
>>: How to change fixed positioning of child elements to absolute positioning by CSS3 transform
Starting from this article, a new series of artic...
Table of contents The problem here is: Solution 1...
1. dhtmlxTree dHTMLxTree is a feature-rich Tree M...
In Node.js, a .js file is a complete scope (modul...
In the UI cutting process, the page is often comp...
This question originated from a message on Nugget...
Preface Sometimes you need to keep the height of ...
Table of contents Inheritance ES5 prototype inher...
Recently, an online security scan found a vulnera...
Install the unzipped version of Mysql under win10...
Mobile Mobile pages only need to be compatible wi...
Original text: http://www.planabc.net/2008/08/05/...
And, many times, maintenance requires your website...
Table of contents 1: Build webpack 2. Data hijack...
The default storage directory of mysql is /var/li...