Kermit
Kermit

Reputation: 3407

Firebase Realtime Database - fetch data while iterating array

How can I fetch data from several nodes in Firebase Realtime Database using an array as source?

The below code does not work, due to syncronous calls.

const myFunction= (snapshot) => {
  const dbRoot = snapshot.ref
  dbPaths = ['one', 'two']

  console.log('myFunction began')

  dbPaths.forEach((dbpath) => {
    const ref = dbRoot.child(dbpath)
    ref.orderByChild('name')
    .equalTo('Donald')
    .once('value', (removeSnapshot) => {
      const dataNode = removeSnapshot.val()
      console.log('myFunction dataNode', dataNode)
      //... logic
    })
  })

  console.log('myFunction finished')
}

The output will be something along the lines of

myFunction began
myFunction finished
myFunction dataNode {data:'somedata'}
myFunction dataNode {data:null}

How can I iterate an array containing the database paths to fetch while waiting for the fetch to finish?

Upvotes: 0

Views: 84

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

As soon as you say "waiting for [asynchronous operation] to finish" think "promises".

In this case, since you're waiting for multiple operations, you're looking for Promise.all:

const dbRoot = snapshot.ref
dbPaths = ['one', 'two']
let promises = [];

console.log('myFunction began')

dbPaths.forEach((dbpath) => {
  const ref = dbRoot.child(dbpath)
  promises.push(
    ref.orderByChild('name')
    .equalTo('Donald')
    .once('value', (removeSnapshot) => {
      return removeSnapshot.val()
    })
  );
})

Promise.all(promises).then((values) => {
  console.log(`All loading finished, all values are in ${values}`) 
})

Upvotes: 1

Related Questions