javascript - Regarding ajax asynchronous loading, please ask about data delay issue
阿神
阿神 2017-06-30 09:53:44
0
6
688

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.

阿神
阿神

闭关修行中......

reply all(6)
为情所困

ajax asynchrony can cause such problems. Solution 1. Promise 2. Assign value in ajax callback

ringa_lee

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.

过去多啦不再A梦

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template