Home > Article > Web Front-end > A simple understanding of the combination of synchronization, closure and asynchronous requests in js
Let’s look at the synchronization request first
The background received is 0~10
The ajax callback output is also 0~10
for (var index = 0; index <= 10; index++) { $.ajax({ async: false,//同步 url: '/HelloWorld', type: 'POST', dataType: 'html', data: {index: index} }).done(function () { console.log(index); }) }
After switching to asynchronous
The data received in the background has changed and is not expected 0~10
ajax The same is true for the callback output, which becomes 11 11
The order of ajax execution is after the for loop execution, i becomes 11
Need to maintain alignment when ajax is executed The reference of i can achieve the expected effect
for (var index = 0; index <= 10; index++) { (function (num) {//形参 $.ajax({ async: true,//异步 url: '/HelloWorld', type: 'POST', dataType: 'html' }) .done(function () { console.log(num); }) })(index)//实参}
In this way, the value received by the background can be consistent with the value output by the foreground
Look at the synchronization request first
The background received is 0 ~10
The ajax callback output is also 0~10
for (var index = 0; index <= 10; index++) { $.ajax({ async: false,//同步 url: '/HelloWorld', type: 'POST', dataType: 'html', data: {index: index} }).done(function () { console.log(index); }) }
After changing to asynchronous,
received by the background The data has changed, which is not the expected 0~10
The callback output of ajax is the same, it has become 11 11
ajax execution After the for loop is executed sequentially, i becomes 11
It is necessary to maintain a reference to i during ajax execution to achieve the expected effect
for (var index = 0; index <= 10; index++) { (function (num) {//形参 $.ajax({ async: true,//异步 url: '/HelloWorld', type: 'POST', dataType: 'html' }) .done(function () { console.log(num); }) })(index)//实参}
In this way, the value received by the background can be compared with the value output by the foreground Values are consistent
Related articles:
ajax Synchronous request and Difference analysis of asynchronous requests
Related videos:
Qianfeng Education PHP asynchronous communication framework Swoole interpretation video tutorial
The above is the detailed content of A simple understanding of the combination of synchronization, closure and asynchronous requests in js. For more information, please follow other related articles on the PHP Chinese website!