This article introduces how to handle javascript multi-concurrency problems, involving knowledge about js multi-concurrency processing methods, if you are interested in js multi-concurrency processing methods, refer to this article and often encounter this scenario when writing code: the loading page is displayed during page initialization, start multiple concurrent ajax requests to obtain data at the same time, and end loading when each ajax request returns.
For example, a page for placing an order needs to query common address information, product information, city information... These requests are asynchronous and we hope to allow user operations after all the data is loaded.
One easy problem to achieve this scenario is how to control multiple concurrency? The following are some solutions and ideas:
Parallel to serial
If the business logic itself is serial, but the request method provided is asynchronous, you can consider this method.
This is obviously not the case in this scenario. This greatly reduces the page performance and speeds up loading.
Callback
Only suitable for scenarios with a small number of concurrent threads, multi-layer nested callback will greatly reduce the readability of the Code
function async1(){ //do sth...}function async2(){ //do sth... async1();}async2();
Change ajax to synchronization
For example, set the async parameter to false in jquery.
$.ajax({ url:"/jquery/test1.txt", async:false});
Set end ID
In a simple way, you can set a counter, add 1 to each asynchronous function, or set an array. Each time an asynchronous function is executed, the array is updated.
Callback count
Var cnt = 0; function async1 () {// do something... callback ();} function async2 () {// do something... callback () ;}function callback () {cnt ++; if (2 = cnt) console. log ('all executed successfully ');}
Loop Blocking
var cnt = 0;function async1(){ //do sth... cnt++;}function async2(){ //do sth... cnt++;}while(2>cnt){}
Non-blocking Loop
It is not recommended to use too much to avoid affecting performance.
Var cnt = 0; function async1 () {// do something... cnt ++;} function async2 () {// do something... cnt ++;} var interval = setInterval (function () {if (2 = cnt) {console. log ('execution completed '); clearInterval (interval )}}
Third-party framework implementation
Jquery
The method I currently use in the project
Var d1 = $. deferred (); var d2 = $. deferred (); function async1 () {d1.resolve ("Fish");} function async2 () {d2.resolve ("Pizza");} $. when (d1, d2 ). done (function (v1, v2) {console. log (v1 + v2 + 'finished ');});
The above content is a small series of related knowledge about how to deal with JavaScript multi-concurrency issues, I hope to help you.