</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-03-14 04:25:21Z" class="relativetime">5 years ago</span>.</div>
</div>
</aside>
I've seen similar questions asked on SO but no quite my problem.
I have something like
var x = 5;
if( some condition ){
$.ajax({
url:"...",
success: function(response){
x = response.x;
}
}
}
some other logic
use x variable
What is happening is the thread executing the JS gets to the logic that uses x before the asynchronous task comes back.
Normally I would just put whatever logic inside the success function but I need the logic to happen regardless of whether or not the condition is met and I don't want to replicate code. Anyone have any suggestions? Should I just async to be false?
Thanks!
</div>
JQuery also has an fail() callback in case the Ajax fails. I'd just put the logic in both cases. (abstracted into a function) Check out this question.
jQuery: Handle fallback for failed AJAX Request
**Revision
$.ajax's complete() method runs after an ajax call no matter what. Sounds perfect. http://api.jquery.com/jquery.ajax/
async false would be one way to go about it since you want the value returned by x to be used if the condition is true.
You could also use promises.
var x = 5;
var ajaxCall;
if(some condition) {
ajaxCall = $.ajax({
url: "...";
});
}
function usingx(x) {
//Add your logic
}
if(typeof(ajaxCall) === 'undefined') {
usingx(x);
} else {
ajaxCall.done(function(data){
usingx(data.x);
});
}
It is either going to async false or you have call the function in two cases, one case where it can execute without waiting and the other in which it has to wait.
A bit more complicated way would be to wait till Ajax gets completed and then run the function.
var x = 5;
var isCallMade = false;
if(some condition) {
isCallMade = true;
ajaxCall = $.ajax({
url: "...";
}).done(function(data){
x = data.x;
}).always(function(){
isCallMade = false;
});
}
function useX() {
if(isCallMade) {
setTimeout(useX, 100); //Wait for ajax call to finish
} else {
//logic using x
}
}
Use the always callback.
if( some condition ){
$.ajax({
url:"...",
success: function(){ // BTW, as of jQuery 1.8 this is referred to as "done"
// Success specific code
},
always: function() {
// Code that always executes regardless of success or failure
}
}
}