title: Firebase - waiting for data from async database call
body: <p>I am trying to fetch some data from firebase with 2 database calls.
  My strategy to get accounts only for 1 user is as follows:</p>
  
  <ul>
  <li>fetch all account numbers for logged in user</li>
  <li>new fetch call to get array of accounts (with all their data)</li>
  <li>dispatch call with full array</li>
  </ul>
  
  <p>My firebase structure look like this.</p>
  
  <p><a href="https://i.stack.imgur.com/qvmLE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qvmLE.png" alt="enter image description here"></a></p>
  
  <p>My problem is that the second fetch call always finishes last.</p>
  
  <pre><code>export const fetchAccounts = () =&gt; {
     return (dispatch, getState) =&gt; {
        const accounts = [];
        const uid = getState().auth.uid;
  
        return database.ref(`users/${uid}/accounts`).once('value').then((snapshot) =&gt; {
           snapshot.forEach((element) =&gt; {
              database.ref(`accounts/${element.key}`).once('value').then((snapshot) =&gt; {
                 accounts.push(snapshot.val());
                 console.log('snapshot: ', accounts);
              })
           });
           console.log('Acc 1:', accounts);
        }).then(() =&gt; {
           console.log('Acc 2:', accounts)
        })
  
        // dispatch call with full array
     }
  };
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/dKMmh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dKMmh.png" alt="enter image description here"></a></p>
  
  <p>I am calling action from main file</p>
  
  <pre><code>  reduxStore.dispatch(fetchAccounts()).then(()=&gt;{
       renderApp();
    });
  </code></pre>
  
  <p>Is it possible to wait for both database calls to finish and then call dispatch function with fully populated array? Appreciate any idea.</p>