How to return a value from a anonymous function?,

I’m trying to have a method that reads something from Firebase Database then returns the Datasnapshot as output. I have the following code:

public DataSnapshot getElements() {
FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://somedatabaseURL.com/");
 FirebaseDatabase.DefaultInstance.RootReference.GetValueAsync().ContinueWith(task => {
             if (task.IsFaulted)
             {
                 Debug.Log("not ok");
          }
             else if (task.IsCompleted)
             {
                DataSnapshot snapshot = task.Result;
                 return snapshot
          }
         });
}

Getting the following error:
“Anonymous function converted to a void returning delegate cannot return a value.”

Searched the answer on all over the internet, couldnt find anything. How to overcome it?,

What you are trying to do is impossible. You can’t expect a synchronous function to directly return something retrieved by an asynchronous function.

You will need to provide a callback to your synchronous function that will be called once your asynchronous function has terminated.

public void getElements( System.Action<DataSnapshot> onSnapshotRetrieved ) {
     
FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://somedatabaseURL.com/");
     
FirebaseDatabase.DefaultInstance.RootReference.GetValueAsync().ContinueWith(task => {
          if (task.IsFaulted)
          {
              Debug.Log("not ok");
       }
          else if (task.IsCompleted)
          {
             onSnapshotRetrieved ( task.Result ) ;
          }
      });
 }

// ...

getElements ( snapshot => Debug.Log( "Snapshot retrieved!" ) ) ;

Hi again @Hellium ,

I have tried your solution but that doesn’t solve my problem since System.Action doesn’t let me return a value. System.Func is also not working, since it doesn’t accept any input.

public void Load(string assetName)
	{
        Debug.Log("1. flag");
        getElements(snapsnapshot => { Debug.Log(snapsnapshot.ChildrenCount); });
        Debug.Log("2. flag");
}

When I run the above snippet with the same getElements method you described, following is printed:

'1. flag'
'2. flag'
'3' (Number of Children)

However, I need it to be like:

'1. flag'
'3' (Number of Children)
'2. flag'

Otherwise it returns a value from the method before assigning the new value. Do you have any comment to this situation?