Often when writing code to encounter such a scenario: page initialization display loading page, while starting multiple Ajax concurrent request to get data, when each AJAX request return to end loading.
For example, a page to place orders, to query the common address information, commodity information, the city information ... These requests are asynchronous and want to wait until all data loads are complete before allowing the user to operate.
One problem that can be easily encountered in this scenario is how do I control concurrency? Here are some solutions and ideas:
Change parallel to Serial
This method can be considered if the business logic itself is serial, but the request method provided is asynchronous.
This scenario is clearly not the case, which greatly reduces page performance and increases load speed.
Callback
For cases with fewer concurrent numbers, multiple nested callbacks can make your code much less readable
function Async1 () {
//do sth ...
}
function Async2 () {
//do sth ...
Async1 ();
}
ASYNC2 ();
Ajax changed to sync
If you set the async parameter to False in jquery
$.ajax ({
URL: "/jquery/test1.txt",
async:false
});
Set End identity
Simple to set the counter, each completes an asynchronous function plus 1, or set an array, every execution of an asynchronous function to update the array.
Callback Count
var cnt = 0;
function Async1 () {
//do sth ...
Callback ();
}
function Async2 () {
//do sth ...
Callback ();
}
function callback () {
cnt++;
if (2==cnt) Console.log (' all completed ');
}
Loop blocking
var cnt = 0;
function Async1 () {
//do sth ...
cnt++;
}
function Async2 () {
//do sth ...
cnt++;
}
while (2>cnt) {}
Loop non-blocking
Do not recommend excessive use, so as not to affect performance
var cnt = 0;
function Async1 () {
//do sth ...
cnt++;
}
function Async2 () {
//do sth ...
cnt++;
}
var interval = setinterval (function () {
if (2===cnt) {
console.log (' performed completed ');
Clearinterval (interval)
}
}
Third-party framework implementation
Jquery
The way I'm currently using 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 + ' completed ');
The above content is small to introduce to you about JavaScript multiple concurrency problem how to deal with the relevant knowledge, I hope to help.