I'm having trouble with a line inside an if statement executing before the conditional is met. What I want to do is:
- Check to see if data (big old array of numbers) is already loaded.
- If not get it and load it into my all_data object.
- Plot data (or in this case alert it)
Here's the code (stripped of many details to be readable
var all_data={};
function get_data(name,rid) {
if (!all_data[name]) {
return $.get('/data.json',
{'name':name},
function(data) {all_data[name]=data;},
"json");
} else {return true}
}
function load_file(name,rid) {
if (get_data(name,rid)) { alert(all_data[name]) };
}
What happens with the above code is that when I execute get_data it immediately alerts "undefined" because the jQuery.get is returning a (not yet completed) request object. At this point the entry all_data[name] is undefined. If I wait ~5s the get request completes, and running the code again will just alert "[Object Object]" because the data has loaded. I realize I could just put a function in both the $.get callback and it the else statement but that would make this no longer generalized. Any thoughts?
Chris