In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to use serial and parallel in JavaScript asynchronous operation". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use serial and parallel in JavaScript asynchronous operation".
1. Preface
This article writes about the schemes of es5 and es6 in js for asynchronous functions, serial execution and parallel execution. Examples that have been used in combination with serial and parallel.
2. Es5 mode
Before es6 came out, there was a promise solution for callback hell in the community nodejs. If there are multiple asynchronous functions, how to arrange the execution in sequence, and how to execute all the asynchronous functions more quickly before performing the next step? Here comes the problem of serial execution and parallel execution of js.
3. Asynchronous function serial execution var items = [1, 2, 3, 4, 5, 6]; var results = []; function async (arg, callback) {console.log ('parameter is' + arg +', return the result in 1 second'); setTimeout (function () {callback (arg * 2);}, 1000);} function final (value) {console.log ('complete:', value) } function series (item) {if (item) {async (item, function (result) {results.push (result); return series (items.shift ()); / / Recursive execution of 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 last one is executed at the end of the next one, similar to async and await in es6 (es6 after es5). Is there any parallel execution like promise.all?
You can write as follows:
Var items = [1, 2, 3, 4, 5, 6]; var results = []; function async (arg, callback) {console.log ('parameter is' + arg +', return the result in 1 second); setTimeout (function () {callback (arg * 2);}, 1000);} function final (value) {console.log ('complete:', value) } items.forEach (function (item) {/ / cycle completion async (item, function (result) {results.push (result); if (results.length = items.length) {/ / determine whether the number of completed execution is equal to the number of functions to be executed final (results [results.length-1]);}); 5. Combination of serial execution and parallel execution of asynchronous functions
If many pieces of asynchronous (hundreds of) data are executed in parallel, and there are a lot of (https) request data in each asynchronous data, it is bound to cause insufficient number of tcp connections, or accumulate numerous call stacks and cause memory overflow. Therefore, it is not easy to execute too much data in parallel, so there is a combination of parallel and serial.
The code can be written as follows:
Var items = [1, 2, 3, 4, 5, 6]; var results = []; var running = 0 setTimeout var limit = 2 role function async (arg, callback) {console.log ('parameter is' + arg +', return the result in 1 second'); setTimeout (function () {callback (arg * 2);}, 1000);} function final (value) {console.log ('complete:', 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 mode
Es6 naturally has its own serial and parallel execution methods, for example, serial can use async and await (explained earlier), parallel can use promise.all, and so on. Then for serial and parallel combination, limit the number of promise all concurrency, the community also has some solutions, such as
Tiny-async-pool 、 es6-promise-pool 、 p-limit
Simply encapsulate a promise all concurrency limit solution function
Function PromiseLimit (funcArray, limit = 5) {/ / concurrently execute 5 pieces of data let I = 0; const result = []; const executing = []; const queue = function () {if (I = funcArray.length) return Promise.all (executing); const p = funcArray [iTunes +] (); 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 to add random failure logic
/ / modify test code randomly failed or succeeded 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 ("failure", data);}); 7, async and await combine promise allasync function PromiseAll (promises,batchSize=10) {const result = []; while (promises.length > 0) {const data = await Promise.all (promises.splice (promises.splice); result.push (.data);} return result;}
There are two problems with writing like this:
1. Promises has been created before Promise.all is called. In fact, promise has already executed it.
2. Your implementation must wait for the previous batchSize promise resolve before you can run the next batch of batchSize, that is, all promise all can be successful.
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 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 = > {...}) Thank you for your reading, the above is the content of "how to use serial and parallel in JavaScript asynchronous operation". After the study of this article, I believe you have a deeper understanding of how to use serial and parallel in JavaScript asynchronous operation. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.