title: Collect results from firebase cloud function async call in a loop
body: <p>I am trying to query firebase data in a loop, then I need to collect data from there create a collection of data and return to the calling function.</p>
  
  <p>Below is my code, and I am unable to collect results and return statement gets executed before all results are collected in the array.</p>
  
  <pre><code>function xyz() {
      ...
      // variable lookupKey is defined above this function
      return dbRef.child(`/location/${lookupKey}`).once('value').then(contacts =&gt; {
          const otherUserNotificationids = []
          contacts.forEach(function(element) {
              var id = element.val()
              console.log(`found id: ${id}`)
              dbRef.child(`/tokenLookup/${id}`).once('value').then(notifId =&gt; {
                  const nVal = notifId.val()
                  console.log(`found notification id : ${nVal}`)
                  otherUserNotificationids.push(nVal)
              })
          });
          const len = otherUserNotificationids.length
          console.log(`found notificationIds count : ${len}`)
          return Promise.all([otherUserNotificationids])
      })
  }
  </code></pre>
  
  <p>As expected the function finishes with 'found notificationIds count : 0', </p>
  
  <p>How do I collect the results from the call to /tokenLookup/${id} and create a collection out of them.</p>
  
  <p>I am doing this, so I do not have to call admin.messasing().sendToDevice() for every token, instead I can just call it once with a array to tokens and its done.</p>
  
  <p>After Doug's response, thought hard about my use of Promises and this is how i resolved it:</p>
  
  <pre><code>function xyz() {
     //moved this variable to top of function (rather then inner scope)
     const otherUserNotificationids = []    
      ...
      // variable lookupKey is defined above this function
      return dbRef.child(`/location/${lookupKey}`).once('value').then(contacts =&gt; {
          const promises = []
          contacts.forEach(function(element) {
              var id = element.val()
              console.log(`found id: ${id}`)
              const prms = dbRef.child(`/tokenLookup/${id}`).once('value').then(notifId =&gt; {
                  const nVal = notifId.val()
                  console.log(`found notification id : ${nVal}`)
                  otherUserNotificationids.push(nVal)
              })
              promises.push(prms)
          });
          return Promise.all(promises).then(res =&gt; {
          const len = otherUserNotificationids.length
          console.log(`found notificationIds count : ${len}`)
          return Promise.all([otherUserNotificationids])
          })
      })
  }
  </code></pre>