6

I have a list of known keys in my Firebase database

-Ke1uhoT3gpHR_VsehIv
-Ke8qAECkZC9ygGW3dEJ
-Ke8qMU7OEfUnuXSlhhl

Rather than looping through each of these keys to fetch a snapshot of their respective object, how can I query for each of these keys in one single, unified request? Does Firebase provide this?

I've discovered the Promise.all() function which looks promising (no pun intended I swear) but I'm not sure how to implement it using the standard way of fetching firebase data like so

var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
  var username = snapshot.val().username;
});

Thanks for any help!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Clay Banks
  • 4,483
  • 15
  • 71
  • 143

1 Answers1

19

As David's comment suggested: if the items are in some way related, you may be able to built a query to get them all.

Otherwise this would do the trick:

var keys = [ 
  "-Ke1uhoT3gpHR_VsehIv",
  "-Ke8qAECkZC9ygGW3dEJ",
  "-Ke8qMU7OEfUnuXSlhhl"
];
var promises = keys.map(function(key) {
  return firebase.database().ref("/items/").child(key).once("value");
});
Promise.all(promises).then(function(snapshots) {
  snapshots.forEach(function(snapshot) {
    console.log(snapshot.key+": "+snapshot.val());
  });
});

Note that retrieving each item with a separate request is not as slow as you may think, since the requests are all sent over a single connection. For a longer explanation of that, see Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly.

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks Frank, very helpful. One question I have is if we're using two separate calls to Firebase - one for geo data, one for location data, we will have two separate lists of objects. Can we easily associate the two lists via the matching keys without having to traverse both lists and takeup more time? (for example, adding geo data to a node with a matching key) – Clay Banks Mar 05 '17 at 18:50
  • Using corresponding keys between the geofire nodes and your regular nodes it the idiomatic way to use Firebase. – Frank van Puffelen Mar 05 '17 at 21:01
  • Good idea on the promises! Thanks for the tip! – Ally Jr Jul 30 '17 at 16:09