You're exactly right in that it is caused by the asynchronicity of the Firebase calls. The kind of system you'll most likely want to employ is one in which you "subscribe" to know when calls have completed. You can use a callback function, or some other method, such as adding a field/piece of data to a list, and having another data structure periodically check the list for updates, in order to know when the async call has completed.
Your flow will probably be something like this:
- "subscribe" to the asynchronous data structure
- tell asynchronous data structure to execute
- on completion of the asynchronous call, perform some action.
I'd recommend looking at the following link on Asynchronous callbacks in Java from Geeksforgeeks: https://www.geeksforgeeks.org/asynchronous-synchronous-callbacks-java/