Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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');
    }
});
share|improve this question
up vote 1 down vote accepted

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');
    }
  });
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.