jquery - AJAX request in for loop returns results out of order -


i'm trying append 10 images #container, in same order they're being requested reasons don't understand they're being returned out of order.

i'm getting urls via for loop , passing them ajax request per below:

for (i = 0; < $links.length; i++) {     link = $links.eq(i).attr('href');      // appends anchor #container     $('#container').append('<a href="' + link + '" class="tile"><p>' + $links.eq(i).text() + '</p></a>');      $.ajax({         type: 'get',         url: link     }).done(function (data) {         var $data = $(data);         $('#container').append($data.find('img').eq(0));     }); }; 

any insight how fix or better great! thanks!

this expected behaviour because requests asynchronous. may fired in order require, response time entirely @ mercy of server , how long takes process each request.

for example, make 3 requests. #1 takes 150ms complete, #2 200ms , #3 75ms. done() handler execute requests in order 3, 1, 2.

if depend on responses being processed in specific order need amend code send data in single request response can formatted require.

the use of async: false may create behaviour expect, incredibly bad practice use, , above solution more preferable.


Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -