Home > Net >  How to get X independents Nodes in one sentence Firebase Realtime DB js
How to get X independents Nodes in one sentence Firebase Realtime DB js

Time:08-18

I want to know if is possible to get some nodes (i have the complete path) in the same request with JS

Example .

  • index
    • key1
    • key2
    • key3
    • key4
    • key5

Actually i do:

get(child(dbRef, `index/` key1)).then((snap) => {
    get(child(dbRef, `index/` key3)).then((snap) => {

    });
});

How can i get key1 and key3 with one sentence (with promises maybe?) Thanks

CodePudding user response:

The Firebase Realtime Database can only get a single path, or a slice of the direct child nodes under that path (through a query). It doesn't have an API to get multiple specific child nodes under a path beyond that.

So you'll indeed need a separate call for each child. But keep in mind that Firebase pipelines those requests over a single (web socket) connection, so this is not nearly as slow as you may initially expect. For more on this, see Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly

If you to simplify the code to wait for both get calls to complete, you can use Promise.all:

Promise.all([
  get(child(dbRef, `index/` key1)),
  get(child(dbRef, `index/` key3))
]).then((snapshots) => {
  snapshots.forEach((snapshot, i) => {
    console.log(i, snapshot.key, snapshot.val());
  });
});
  • Related