</div>
</div>
<div class="grid--cell mb0 mt4">
<a href="/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call" dir="ltr">How do I return the response from an asynchronous call?</a>
<span class="question-originals-answer-count">
(38 answers)
</span>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2015-01-16 17:04:31Z" class="relativetime">5 years ago</span>.</div>
</div>
</aside>
I'm working in javascript and AJAX. I make a call to a server to log in. It sends a response that the login was true. Then I need to collect all the information about the user by making a call to the server again. If I make the call immediately, the server will send back a response that the user is not logged in. I can use either setTimeout(myFunction(), 1000) or setInterval(myFunction(), 1000); to make the second call. I was wondering, is there a clean way to wait for the proper response before continuing without the rest of the code running? I guess my biggest question would be, how could I do this without putting everything in the callback response? I want the code to be somewhat modular.
</div>
You need to program using asynchronous techniques. A typical Ajax call in jQuery and then processing the response would look like this:
$.ajax(...).then(function(result) {
// put code here that uses the result
// then continue on with other code that should run after the result was processed
});
// code here will run BEFORE the ajax call completes
If you want to run one ajax call and then another one after that, you can either chain them or you can run the second from within the completion callback of the first:
$.ajax(...).then(function(result) {
// process result of the first
// run second ajax call
return $.ajax(...)
}).then(function(secondResult) {
// code here when second ajax call is done
});