A simple solution could be to create a function that takes an argument and utilizes it twice - once for the request and again to "store" the result.
var myData = {};
function getDate(date) {
$.getJSON("http://127.0.0.1:8080/horizon-update?date="+date, function(data){
myData[date] = data;
});
}
getDate('date1');
getDate('date2');
getDate('date3');
This code does not account for the asynchronous nature of the request, which is also true for the original code in the question.
Note: I updated the name of the result object in the callback and the variable where the result is saved to emphasize that it is not JSON - even though the returned data might be JSON, jQuery.getJSON returns the parsed JSON as a regular JavaScript object.
A more suitable approach would be something like this:
function getDate(date) {
return $.getJSON("http://127.0.0.1:8080/horizon-update?date="+date);
}
$.when(getDate('date1'), getDate('date2'), getDate('date3'))
.then(function(result1, result2, result3) {
// the results are now available
})
If the number of calls is dynamic, the logic becomes more complex (especially with jQuery.when):
function getDate(date) {
return $.getJSON("http://127.0.0.1:8080/horizon-update?date="+date);
}
var dates = ['date1', 'date2', 'date3'];
$.when.apply($, dates.map(function(date) {
return getDate(date);
}).then(function() {
// the results are in arguments[]
})
Since jQuery.getJSON returns a thenable
(promise), you can simplify the code using Promise.all
. To support IE, a Promise polyfill is necessary. This linked one is referenced in the MDN Promise docs, but there are many other options available.
function getDate(date) {
return $.getJSON("http://127.0.0.1:8080/horizon-update?date="+date);
}
var dates = ['date1', 'date2', 'date3'];
Promise.all(dates.map(function(date) {
return getDate(date);
}).then(function(results) {
// results is an array containing all the results in the same order as the dates array
})