Often when writing code to encounter such a scene: The page is initialized to display the loading page, while initiating multiple AJAX concurrent requests to obtain data, when each AJAX request returns the end of loading.
For example, a page to place an order, to query the general address information, commodity information, land city information ... These requests are asynchronous and want to wait until all data is loaded and then allow the user to operate.
One of the most difficult problems to achieve in this scenario is how much concurrency is controlled? Here are some workarounds and ideas:
parallel changes to serial
This method can be considered if the business logic itself is serial, but the requested method is provided asynchronously.
This scenario is obviously not the case, which greatly reduces page performance and increases loading speed.
Callback
Multi-layered nested callbacks can make code less readable when only the number of concurrent cases is appropriate
Java code
function Async1 () { //do sth ... } function Async2 () { //do sth ... Async1 (); }
Ajax changed to synchronous
For example, set the async parameter to False in jquery.
Java code
$.ajax ({ URL: "/jquery/test1.txt", async:false });
Set End ID
A simple one can set the counter, each completion of an asynchronous function plus 1, or set an array, each execution of an asynchronous function update array.
Callback Count
JS Code
var cnt = 0; function Async1 () { //do sth ... Callback (); } function Async2 () { //do sth ... Callback (); } function callback () { cnt++; if (2==cnt) console.log (' all executed ');
Cyclic blocking
Java code
var cnt = 0; function Async1 () { //do sth ... cnt++; } function Async2 () { //do sth ... cnt++; } while (2>cnt) {}
cyclic non-blocking
Not recommended for excessive use, so as not to affect performance
JS Code
var cnt = 0; function Async1 () { //do sth ... cnt++; } function Async2 () { //do sth ... cnt++; } var interval = setinterval (function () { if (2===cnt) { console.log (' executed completed '); Clearinterval (interval) } }, 0);
third-party framework implementations
jquery
The way I'm currently using the project
Java code
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 + ' completed ');
Angular
The specific code is not written, you can refer to the API documentation for $watch instructions.
JS Simple solution Concurrency Volume