Having an array temp1
with this pattern:
[{"group":"Test","keywords":["Hund","Katze"]}]
I'm able to make API requests for getting synonyms of each element of temp1.keywords
with the following function:
consultSynonyms(temp1)
function consultSynonyms(x) {
// create an empty array where all the responses are gping to be pushed
// format has to be: [{x: xvalue, y: yvalue, z:zvalue...}]. This array
// will be passed to data table plugin
var jsonSynonyms = [];
$.each(x, function(i, value) {
// get name of group (f.i. Test)
var superGroup = value.group;
$.each(x[i].keywords, function(i, value) {
// get term (f.i. Hund) and iterate all the terms
var term = value;
$.ajax({
type: "GET",
dataType: "jsonp",
url: "https://www.openthesaurus.de/synonyme/search?q=" + term + "&format=application/json&supersynsets=true",
success: function(data) {
$.each(data.synsets, function(key, value) {
// get category (f.i. "Biology") from response
var category = this.categories[0];
$.each(this.terms, function(key, value) {
// synonym is every term delievered by the API Call
// level is also delievered (f.i.: "formal", "informal"...)
var synonym = this.term;
var level = this.level;
jsonSynonyms.push({
group: superGroup,
keyword: term,
category: category,
term: synonym,
level: level
});
});
});
}
});
});
});
console.log(jsonSynonyms);
}
However, the last console.log
doesn´t deliver the expected output but a simple []
. I am sure that the ajax code is correct, because if I move the console.log inside the function(data)
, I get the expected output:
[{"group":"Unnamed group","keyword":"Hund","category":"Biologie","term":"Hund"},{"group":"Unnamed group","keyword":"Hund","category":"Biologie","term":"Vierbeiner"}...]
As far as I'm corcerned, the console.log at the end of my function is evaluated at the very end, and therefore I don't understand why I'm getting the blank array, while evaluating it at the middle of the function delivers a correct output. Any hint for this behaviour?