Asynchronous Actions

Last Updated: 16 March 2023

Learn about Asynchronous Actions 

The image above is a snapshot of the Firebase Realtime Database Action list.

Most Firebase functions such as reading or writing data requires some time to complete because it involves interactions with servers (such as loading data from a server or sending data to it). 

The "arrow-around-clock" icon in the image indicates that the corresponding actions are Asynchronous. While such an action is still running (for eg. when some data is being fetched from the Firebase servers), other actions continue executing, one after the other. 

Actions execute in the order they are placed in. A synchronous action will stop the next action from starting until it is completed. But an asynchronous action will allow the next action to start even when it is still executing. 

But why all the trouble? Why are the Firebase actions asynchronous? This is because Synchronous actions are supposed to execute really fast- mostly within a few hundred microseconds. They happen so fast that you usually get a seamless experience.

But in case of Asynchronous actions, loading data or writing takes at least a few seconds in a normal network speed and for that time duration you don’t want the next actions to stop executing. If your Asynchronous actions were forced to be synchronous, your game would have looked like it freezed. You don’t want that. So you can think of it like each asynchronous action execute in background in different threads while the synchronous actions execute in-front, one by one.

Example: How to Read Data from Realtime-Database

This example above is a wrong way to use a Database function.

In the example, “Read User Data” action is asynchronous, and “Set text” action is synchronous. Here, the user won’t get any text in the output (Output will be null). This is because, “Read User Data” will take some time to fetch data from the Firebase server, and as it is asynchronous, it will allow the next action, “Set text” to start even though it has not completed fetching. 

So follow any of these three examples below according to your requirements: 

1. You can use “On” trigger condition. On Data Changed conditions will be triggered every time there is any change in the Read data location. So, Sync data will work. (Recommended in most cases) 

2. Conditions such as Data is Read will run every tick and hence, the text will also be set every tick.

3. “Wait for previous actions to complete” makes the next actions wait until the previous actions are completed. 

NOTE-  If you are using this method, Sync parameter must be set to False. “Wait for previous actions to complete” will work only if sync is disabled.