1

I'm trying to build an application with Ionic Framework and Javascript, and I want to fetch all the data from a table in an array, but when I try to access that array outside the function it's empty. I've read something that maybe the array gets populated after the console.log("length "+ $scope.cards.length); but I don't know how to solve this so I can use the array after that.

This is the function for fetching the data from the table(it works):

 fetchCards: function(success) {
  database.transaction(function(tx) {
    tx.executeSql("SELECT cardId, name, chosen, filePath, found FROM Cards", [], 
      function (tx, results) {
        console.log('success select ' + results);
        cards = [];
        for (i = 0; i < results.rows.length; i++) {
          cards.push(results.rows.item(i));
        }
        success(cards);
      }, 
      function () {
        console.log('error select');
      });
  });
}

This is where I try to access the array, in a controller:

    .controller('kindergartenController', function($scope, $ionicSideMenuDelegate,service) {

     //list with the difficulties
     $scope.difficultyList=[
     {text:"Easy", value:"easy"},
     {text:"Medium", value:"medium"},
     {text:"Hard", value:"hard"}];

     $scope.data={difficulty:''};

    //redirecting if it presses 
    $scope.goToAnimalsGame = function() {


    if($scope.data.difficulty=='easy'){
      window.location = "#/menu/animalseasy";

      //in this array I want the results
      $scope.cards=[];

      game = new Game(1,"easyAnimalGame");
      console.log("created a new game " + game.getName());
      game.createMemoryGame();

      console.log("difficulty " + $scope.data.difficulty);
      randomNumbers=game.randomNumbers($scope.data.difficulty);
      console.log('Random numbers are:');
      for(i=0;i<randomNumbers.length;i++){
        console.log(randomNumbers[i]);
      }

      //here is where I call the other function, to get data from database
      service.fetchCards(function(cards) {
        $scope.cards = cards;
      //it shows the good length
        console.log("length "+ $scope.cards.length);
      });
      //it shows it's empty
      console.log("length "+ $scope.cards.length);
}

Any suggestions are helpful, thank you.

1 Answer 1

1

It will show empty because:

service.fetchCards

is Asynchronous, therefore inside that function where you define your anonymous callback, won't fire till the data is retrieved.

the console.log("length ".... outside of the function will be executed immediately after the function call fetchCards, but possibly before the callback where the array gets populated.

Unfortunately you can only deal with the populated array within the callback or from a function fired within the callback.

Here is a timeline of execution to aid:

service.fetchCards();

->

console.log("length "....) below the above function

->

anonymous callback (function (cards){}) inside the service.fetchCards()

If that makes sense.

The asynchronism of the service means that the callback you defined anonymously could fire at any time.

The solution:

service.fecthCards(function (data) {
    // do your code
    $scope.cards = cards;
    //it shows the good length
    console.log("length "+ $scope.cards.length);

    // manipulate the array within this function or get it to call another function like so
    nowContinue();
});

function nowContinue() {
    // continue what ever it was that you wanted to do using the newly populated information
}

Because nowContinue is called with in the anonymous callback it will fire whenever the callback gets fired, and will execute after you have populated the controllers local variables with data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.