Reputation: 13425
I've got a piece of code set up to check a condition, and based on that condition, either execute an ajax call to get a JSON object, or proceed to another form of processing. After the processing, I then do some stuff based on the data processed in the if/else statement.
I'm running into a problem, however. The code executes the if/else, and then continues on before the .get is finished processing, and thus my last bit of code doesn't work properly. Is there a way to delay the processing of the rest of the code until the .get is completed?
The structure of my code is as follows:
if(filename != undefined){
$.get(filename, function(json){
$.each(json, function(data){
// Do stuff with the json
});
}, "json");
} else {
// Do some other processing
}
// Do some additional processing based on the results from the if/else statement
// This bit is getting processed before the .get has finished doing it's thing
// Therefore there isn't anything for it to act upon
Upvotes: 0
Views: 706
Reputation: 1821
Use the async: false
option for $.get
to make synchronous requests. http://api.jquery.com/jQuery.ajax/
NOTE:
@Neal: "this is not always the best option. especially if the ajax request hangs for too long."
Upvotes: 1
Reputation: 146300
Make a callback function instead for the rest of the operation:
if(filename != undefined){
$.get(filename, function(json){
$.each(json, function(data){
// Do stuff with the json
doTheRest();
});
}, "json");
} else {
// Do some other processing
doTheRest();
}
function doTheRest(){
// Do some additional processing based on the results from the if/else statement
}
Just remember variable scopes, and if you have to, pass parameters into the doTheRest
function.
Upvotes: 3