动态创建一个数组,然后循环通过另一个数组进行比较,如果数据存在

时间:2016-02-05 16:47:45

标签: javascript arrays angularjs loops

我想要实现的是动态创建一个数组,然后使用该数组与另一个数组进行比较(如果存在数据)。

现在正在发生的事情是,在数组完成创建之前,比较数组的代码正在执行。基本上我将我的数据与空数组进行比较。

我可以使用什么技术让代码完全执行code a然后在code a完成后执行code b

var awayTeamPlayersPlayedArray = [];
vm.awayTeamPlayers = $firebaseArray(awayTeamPlayersQuery);

// add data to awayTeamPlayersPlayedArray
angular.forEach(vm.awayTeamPlayersPlayed, function(value, key) {
    var awayTeamPlayerRef = new Firebase(FIREBASE_URL + 'players/' + key);
    var awayTeamPlayer = $firebaseObject(awayTeamPlayerRef);
    awayTeamPlayer.$loaded().then(function() {
        awayTeamPlayersPlayedArray.push(awayTeamPlayer.name);
        console.log(awayTeamPlayersPlayedArray)
    });
});

// loop through vm.awayTeamPlayers to see if they exist in awayTeamPlayersPlayedArray
angular.forEach(vm.awayTeamPlayers, function(value, key) {
    if(awayTeamPlayersPlayedArray.indexOf(value.name) > -1) {
        console.log(value.name + ' yes');
    } else {
        console.log(value.name + ' no');
    }
});

1 个答案:

答案 0 :(得分:1)

在所有Promise完成后你应该使用循环。

var allPromises = [];
// add data to awayTeamPlayersPlayedArray
angular.forEach(vm.awayTeamPlayersPlayed, function(value, key) {
  var awayTeamPlayerRef = new Firebase(FIREBASE_URL + 'players/' + key);
  var awayTeamPlayer = $firebaseObject(awayTeamPlayerRef);
  var promise = awayTeamPlayer.$loaded().then(function() {
    awayTeamPlayersPlayedArray.push(awayTeamPlayer.name);
    console.log(awayTeamPlayersPlayedArray);
  });
  allPromises.push(promise);
});
$q.all(allPromises).then(function() {
  // loop through vm.awayTeamPlayers to see if they exist in awayTeamPlayersPlayedArray

  angular.forEach(vm.awayTeamPlayers, function(value, key) {
    if(awayTeamPlayersPlayedArray.indexOf(value.name) > -1) {
      console.log(value.name + ' yes');
    } else {
      console.log(value.name + ' no');
    }
  });
});