Define an empty array outside, then make an ajax request, nest another request within the request, and finally splice it into three objects and insert the empty array.
Then I print the length of the array on the outermost side, and the printed length is 0. This problem will affect the assignment. Please tell me how to solve it.
ajax asynchrony can cause such problems. Solution 1. Promise 2. Assign value in ajax callback
ajax is asynchronous. When your log code is executed, ajax has not returned yet.
Please check the event loop issue
We know that ajax is an asynchronous operation,
The location of your console.log. At this time, arr.length is actually [].length
After your current js is executed, the ajax success callback will be executed. Only after the success callback is successful, your arr array will be pushed into the value
So you may want to put console.log into the second ajax success callback
As for promise, it will optimize this nested callback very well, but you need to encapsulate your ajax
It is recommended to wrap all your ajax into promises
ajax is an asynchronous data acquisition method, so the asynchronously acquired data cannot be processed in the synchronous way we usually understand. You should write your console.log in the success callback function.
Set your async: false so that you can get the value inside from the outside.
In this case, you have to change to ajax synchronization. If it is asynchronous, ajax and the code behind it are executed at the same time