函数外部的数组是空的,试图在Javascript中从数据库中获取数据

时间:2014-06-28 23:19:58

标签: javascript arrays

我正在尝试使用Ionic Framework和Javascript构建一个应用程序,我想从数组中的表中获取所有数据,但是当我尝试在函数外部访问该数组时它是空的。我读过一些可能在console.log("length "+ $scope.cards.length);之后填充数组的东西,但我不知道如何解决这个问题,所以我可以在那之后使用数组。

这是从表中获取数据的功能(它可以工作):

 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');
      });
  });
}

这是我尝试在控制器中访问数组的地方:

    .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);
}

任何建议都有帮助,谢谢。

1 个答案:

答案 0 :(得分:1)

它将显示为空,因为:

service.fetchCards

是异步的,因此在您定义匿名回调的函数内部,在检索数据之前不会触发。

函数外部的console.log("length "....将在函数调用fetchCards之后立即执行,但可能在数组被填充的回调之前执行。

不幸的是,您只能处理回调中的填充数组或来自回调中触发的函数。

以下是执行援助的时间表:

service.fetchCards();

- &GT;

console.log("length "....)低于上述功能

- &GT;

anonymous callback (function (cards){})

中的

service.fetchCards()

如果这是有道理的。

服务的异步意味着您匿名定义的回调可能随时触发。

解决方案:

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
}

因为在匿名回调中调用了nowContinue,所以只要回调被触发就会触发,并且在用数据填充控制器局部变量之后执行。