0

What I am trying to achieve is to create an array dynamically and then use that array to compare with another array if data exist.

What is happening right now is that the code to compare the arrays is executing before the array is finish creating. Essentially I am comparing my data to an empty array.

What technique can I use to make the code execute code a completely then when code a is finished execute 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 Answer 1

1

You should use loop after all Promises will be finished.

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