0

See the following JavaScript:

(function() {
    var allMatches = [];

    $.getJSON("myURL", function(data) {
        $.grep(data.feed.entry, function(element, index) {
            var match = {
                day: element.gsx$day.$t,
                winner: element.gsx$winner.$t,
                field: element.gsx$field.$t,
                time: element.gsx$time.$t,
                grade: element.gsx$grade.$t,
                round: element.gsx$round.$t,
                teamOne: element.gsx$team1.$t,
                teamOneGoals: element.gsx$goals.$t,
                teamOnePoints: element.gsx$points.$t,
                teamOneTotal: element.gsx$totalscore.$t,
                teamTwo: element.gsx$team2.$t,
                teamTwoGoals: element.gsx$goals_2.$t,
                teamTwoPoints: element.gsx$points_2.$t,
                teamTwoTotal: element.gsx$total.$t
            }
            allMatches[index] = match;
        });
    });

    var fridayMatches = SQLike.q(
        {
            Select: ['*'],
            From: allMatches,
            Where: function(){return this.day === "Friday"},
            OrderBy: ['field','|asc|']
        }
    );

    console.log(fridayMatches);

})();

If I put a breakpoint at allMatches[index] = match; I can clearly see this array being populated fully

However, if I put a breakpoint further down at the start of my SQLike code allMatches is completely empty.

Why is this, and what is the solution?

DJ180
  • 18,724
  • 21
  • 66
  • 117
  • 1
    That's because the `SQLike.q()` call is happening immediately as the code runs, while the other block is *asynchronously* run, meaning it does something and runs it's callback at a later time (when it gets a response). If you want that second block to run, put it inside the callback for `$.getJSON()`. – Jared Farrish Aug 16 '14 at 17:46
  • If you put both breakpoints, you will see that the one of the SQLike code is met **before** the ajax callback. – Bergi Aug 16 '14 at 19:35

2 Answers2

1

Becouse $.getJSON is asynchronous.

You have to put your SQlite code in a function and call it from the $.getJSON callback.

Callebe
  • 1,087
  • 7
  • 18
1

$.getJSON is does an Ajax call and the "a" in Ajax standards for asynchronous.

The anonymous function that you use to handle the ajax response won't run until the ajax call is returned.

beardedlinuxgeek
  • 1,652
  • 16
  • 26