0

I have two post requests I'm making utilizing jquery and a method that uses the result of those posts. So the code works like this:

 post1 post2 function 

How do I get the code to wait until both post1 and post2 are completed before calling the function? I tried doing a while loop to see if the data from post1 and post2 had both been set, but it hangs the browser. I could call them synchronously, but that would be slower than setting off both requests and waiting for them to complete. This would be easy to solve in any multithreaded language except for JavaScript since officially it's not suppose to be multithreaded and thus has no support for waiting for a series of "threads" to complete.

2 Answers 2

2

Keep a count of the requests, and in your callback modify it then see if there are any left to run.

var count = 2; var callback = function () { count--; if (!count) { both_ajax_called_successful(); } }; jQuery.ajax({url: 'example1', success: callback}); jQuery.ajax({url: 'example2', success: callback}); 
Sign up to request clarification or add additional context in comments.

1 Comment

This. It's important to do this in a callback instead of potentially using a setTimeout to monitor how many ajax calls have been completed.
1

Declare a counter with the value being the number of requests and subtract one off its value every time you get a response. When the value is 0, all requests should be done.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.