0

I'm trying to work out why this function isn't pushing my item as an object to the availableProviders array within my if statement.

serviceProviders.on('value', function(snapshot) {
  var availableProviders = [];

  snapshot.forEach(function(childSnapshot) {
    var key = childSnapshot.key();

    providers.on('value', function(snap) {
      if (snap.hasChild(key)) {
        var item = snap.child(key);
        availableProviders.push(item);
      }
    });
  });

  console.log(availableProviders);
});

For some reason my console.log at the end just returns an empty array.

Any reason why my item isn't being pushed. Any help is appreciated. Thanks in advance!

realph
  • 3,941
  • 12
  • 38
  • 93
  • 1
    providers is async and console.log is sync?...my guess – FPcond Apr 26 '15 at 00:37
  • possible duplicate of [Asynchronous access to an array in Firebase](http://stackoverflow.com/questions/27049342/asynchronous-access-to-an-array-in-firebase) – Frank van Puffelen Apr 26 '15 at 00:51
  • @FrankvanPuffelen Hmm, should I still stay away from `$loaded` in this case? Is there another way to return a promise? – realph Apr 26 '15 at 00:58
  • angularjs works well with Firebase and has promises https://egghead.io/lessons/angularjs-promises – FPcond Apr 26 '15 at 01:10
  • @FPcond So let me get this right, `console.log(availProviders)` is running earlier because it's still waiting for my `providers.on()` to load? – realph Apr 26 '15 at 01:12
  • @realph: yes, which is what the post I linked (and the ones that in turn links to) explains. Put a few `console.log('1');`, `console.log('2');`, etc in there and you can easily see what the order of execution is. – Frank van Puffelen Apr 26 '15 at 03:16
  • @FrankvanPuffelen What's the best way to handle this going forward then? Using the promises built in to Angular, like @FPcond linked to. Or using the promises in Firebase? I ask because in a previous question (http://stackoverflow.com/questions/29849494/using-numchildren-in-angularfire) you mentioned using `$loaded` with caution. – realph Apr 26 '15 at 19:38
  • Promises are fine, callbacks are fine too. But neither of them will do you much good, until you understand and embrace the asynchronous nature of synchronizing data with Firebase. The answer I linked to above and probably all the answers linked from there, give a thorough introduction into asynchronous loading. – Frank van Puffelen Apr 26 '15 at 22:17
  • I added an update to this answer: http://stackoverflow.com/a/26403301/209103 , since I get the feeling people upvote it for the wrong reason. See the answer for the correct way to debug your data as it's loaded (which I shamelessly copied from the Firebase docs). – Frank van Puffelen Apr 26 '15 at 22:32

0 Answers0