I have setup my JavaScript thus
function getData(uri) {
var $result;
var demoAPI = uri;
$.getJSON(demoAPI, function(data) {
$.each(data, function(key, val) {
names[key] = val["name"];
numbers.push(val["number"]);
});
}).done(function() {
for(i = 0; i < names.length; i++) {
var tmp = new Array(names[i], numbers[i]);
result.push(tmp);
}
return result;
});
}
Problem is, with this setup is I cannot use the function thus:
var values = getData('/users');
as the return
statement is in a closure within the $.getJSON
block, if I do call the return
after said block it returns an empty array because it gets called before the ajax call is completed. I will encounter the same challenge if I attempt to use $.ajax()
. I need help returning the generated array from my function getData()
.