title: Firebase cloud function promises
body: <p>I'm having a hard time getting a promise chain to flow correctly in a firebase cloud function. It loops through a ref and returns an array of emails for sending out notifications. It has some nested children, and I think that's where I'm going wrong, but I can't seem to find the error.</p>
  
  <p><strong>/courses structure</strong></p>
  
  <pre><code>{
    123456id: {
      ..
      members: {
        uidKey: {
          email: some@email.com
        },
        uidKey2: {
          email: another@email.com
        }
      }
     },
     some12345string: {
       // no members here, so skip
     }
  }
  </code></pre>
  
  <p><strong>function.js</strong></p>
  
  <pre class="lang-js prettyprint-override"><code>exports.reminderEmail = functions.https.onRequest((req, res) =&gt; {
    const currentTime = new Date().getTime();
    const future = currentTime + 172800000;
    const emails = [];
  
    // get the main ref and grab a snapshot
    ref.child('courses/').once('value').then(snap =&gt; {
      snap.forEach(child =&gt; {
        var el = child.val();
  
        // check for the 'members' child, skip if absent
        if(el.hasOwnProperty('members')) {
  
          // open at the ref and get a snapshot
          var membersRef = admin.database().ref('courses/' + child.key + '/members/').once('value').then(childSnap =&gt; {
            console.log(childSnap.val())
            childSnap.forEach(member =&gt; {
              var email = member.val().email;
              console.log(email); // logs fine, but because it's async, after the .then() below for some reason
              emails.push(email);
            })
          })
        }
      })
      return emails  // the array
    })
    .then(emails =&gt; {
      console.log('Sending to: ' + emails.join());
      const mailOpts = {
        from: 'me@email.com',
        bcc: emails.join(),
        subject: 'Upcoming Registrations',
        text: 'Something about registering here.'
      }
      return mailTransport.sendMail(mailOpts).then(() =&gt; {
        res.send('Email sent')
      }).catch(error =&gt; {
        res.send(error)
      })
    })
  })
  </code></pre>