Real-Serious-Games / C-Sharp-Promise

Promises library for C# for management of asynchronous operations.
MIT License
1.19k stars 149 forks source link

Some general questions about handling promises #91

Closed kevbrun closed 5 years ago

kevbrun commented 5 years ago

Hello!

I am using the Unity Rest Framework which is based on this C-Sharp-Promise library. I hardly can understand, how I can use the downloaded json outside of the promise. I generally do not understand how I can return information to the outside scope.

Like this example here:


          RestClient.Request(request).Then(response =>
                    {

                        UberDebug.LogChannel(LogChannels.NETWORK, "Received from Server : " + response.Text);
                        return response.Text;

                    }).Then(restext =>GetResponseByText(restext)).Then(jsonObj =>UnWrapModel(jsonObj))
                 .Then(message =>
                 {

                     elementToUpdate = message;
                     UberDebug.Log("message "+message);

                 }).Catch(error => { UberDebug.LogErrorChannel(LogChannels.NETWORK, error.Message); });

The variable elementToUpdate of type ModelData is always null after leaving the promise. I read several documentations but I do still not understand. How I can update my data with the information of my server.

Can somebody give me a hint?

Regards K

ashleydavis commented 5 years ago

The then and catch callbacks are invoked asynchronously at some later time.

Meanwhile your subsequent code continues to execute. So when the outside scope resumes your promise hasn't yet resolved which means elementToUpdate hasn't yet been set.

You can't reliably access values from your promise callbacks in the outside scope. You shouldn't even try, because if the promise did happen to resolve quickly enough for this to work you wouldn't be able to rely on the result.

ashleydavis commented 5 years ago

For more help on promises, there's various articles on my old blog you should read.

http://www.what-could-possibly-go-wrong.com

Syslos94 commented 5 years ago

Hi @kevbrun, have you find a solution for your case? I have the same problem but still can't figure out how to solve it.