Here is the contents of get.json:
{ “id” : 1, “name” : “hello” }
and the script/markup:
var entries = [];
function Data(){}
Data.prototype.get = function(id){
var object = {}, length = entries.length, success = false;
for (var i = 0; i < length; i++) {
if (entries[i].id == id) {
object = entries[i];
i = length;
console.log("From browser: " + object.name);
success = true;
}
}
if (!success) {
$.getJSON("get.json", function(data){
entries.push(data);
object = data;
console.log("Newly fetched: " + object.name);
});
}
return object;
}
$(function(){
var data = new Data();
data.get(1);
console.log((data.get(1).name);
});
I would use a callback. If the data exists in the browser cache, the callback will be fired immediately. If not, it will be fired when the Asynchronous request finishes.
Another way would to be to make your AJAX call synchronous which would pause all execution, but that is a very bad idea.
Edit: I also changed your code a little to remove the
successvariable, and chose to return right from theforloop (thereby breaking the loop).