I often encounter this scenario when writing code: the loading page is displayed when the page is initialized, multiple ajax concurrent requests are started to obtain data, and loading ends when each ajax request returns.
For example, a page for placing an order needs to query common address information, product information, city information...and these requests are asynchronous. It is hoped that the user will not be allowed to operate until all data is loaded.
A problem that is easy to encounter when implementing this scenario is how to control multiple concurrency? Here are some solutions and ideas:
Parallel changed to serial
If the business logic itself is serial, but the request method provided is asynchronous, you can consider this method.
But this is obviously not the case in this scenario. Doing so greatly reduces page performance and prolongs loading speed.
Callback
Only suitable for situations where the number of concurrencies is small. Multiple levels of nested callbacks will greatly reduce the readability of the code
function async1(){ //do sth... } function async2(){ //do sth... async1(); } async2();
ajax changed to synchronization
Set the async parameter to false in jquery
$.ajax({ url:"/jquery/test1.txt", async:false });
Set end flag
A simpler approach can be to set up a counter that increments by 1 every time an asynchronous function is completed, or set up an array and update the array every time an asynchronous function is executed.
Callback Count
var cnt = 0; function async1(){ //do sth... callback(); } function async2(){ //do sth... callback(); } function callback(){ cnt++; if(2==cnt) console.log('都已执行完毕'); }
Loop blocked
var cnt = 0; function async1(){ //do sth... cnt++; } function async2(){ //do sth... cnt++; } while(2>cnt){}
Loop non-blocking
It is not recommended to use it too much to avoid affecting performance
var cnt = 0; function async1(){ //do sth... cnt++; } function async2(){ //do sth... cnt++; } var interval = setInterval(function(){ if(2===cnt){ console.log('已执行完成'); clearInterval(interval) } }
Third-party framework implementation
jquery
The current approach I use in my 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 + '已完成'); });
The above content is the relevant knowledge introduced by the editor on how to deal with multiple concurrency issues in JavaScript. I hope it will be helpful to you.