0

I have read many different posts about how to use done() with $.ajax(). As I understand it, ajax returns a promise so the done() should be executed on completion, which seems to be happening, however when in an each() loop, once the first ajax function is reached, the 2nd loop initiates while the first loop is still processing.

Here is a basic jsfiddle of the issue:

https://jsfiddle.net/kLja50xa/1/

My desired result is:

1-1 2-1 1-2 2-2

I have tried the option to push the requests to an array, but this means more nestsed each() ajax() loops with the same issue?

The reason I need to process these in order is that some instances within the loop require user input.

I can force the required result using async:false. but for obvious reasons I want to avoid this. Also this has additional impacts to the script whereby I cannot target and update a tracking message advising the user where the process is.

2
  • 1
    If you want to enforce ordering, then you can't just fire all asynchronous requests at once. Commented Aug 11, 2017 at 12:45
  • @Phylogenesis - I do not want to fire them all at once, which is why I am using the done() to fire the next request once the result of the first one have been received. Do you have a suggestion on how to do this? Commented Aug 11, 2017 at 12:51

1 Answer 1

1

I don't think is possible with a loop.... try using a function that will call it self once the ajax is done

fiddle

eachArray(array);

function eachArray(array){
    $i++;
  console.log('1-'+$i);
    ajax.done(function() {
    console.log('2-'+$i);
    if($i<array.length){
        eachArray(array);
    }
  })
}

Another ES6 cool feature will be using generators is actually a function that pauses its code until you called again

Sign up to request clarification or add additional context in comments.

1 Comment

Fantastically simple! Thanks you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.