0

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?

agustin
  • 1,311
  • 20
  • 42

1 Answers1

1

You use an AJAX request which begins asycnchronous execution of the code inside it. And once you go async, you never go back.

You see, jsonSynonyms won't be populated until after the AJAX call comes back. That may be any amount of time, probably 100-200ms. However, your console.log(jsonSynonyms) code executes immediately after the AJAX call is made. So jsonSynonyms could not have been populated.

You can only use the populated jsonSynonyms after the AJAX call has come back. That means you should use it within the actual AJAX callback.

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); // look at me now!
                    }
                });
            });
        });

    } 
aaronofleonard
  • 2,546
  • 17
  • 23