search

Home  >  Q&A  >  body text

javascript - Regarding ajax asynchronous loading, please ask about data delay issue

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.

阿神阿神2749 days ago712

reply all(6)I'll reply

  • 为情所困

    为情所困2017-06-30 09:55:44

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

    reply
    0
  • ringa_lee

    ringa_lee2017-06-30 09:55:44

    ajax is asynchronous. When your log code is executed, ajax has not returned yet.

    reply
    0
  • 欧阳克

    欧阳克2017-06-30 09:55:44

    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

    reply
    0
  • 为情所困

    为情所困2017-06-30 09:55:44

    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.

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-30 09:55:44

    Set your async: false so that you can get the value inside from the outside.

    reply
    0
  • 巴扎黑

    巴扎黑2017-06-30 09:55:44

    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

    reply
    0
  • Cancelreply