C
C#2y ago
wedman

❔ Async function seems to continue running after returning.

Hi there I'm doing a post request to a REST API. I can see that the callback is running in the console when its printing the Debug.Log. So I would assume that the function would return a User that isn't null but it doesn't. I'm a bit new to asynchronous code and would love to know if I got all of this wrong and if you know a solution to my problem.
public static async Task<User> SignInAnonymous() {
RestClient.Post<ExchangeRefreshTokenResponse>(currentRequest).Then(response => {
Debug.Log(("IDTOKEN: " + response.id_token, "REFRESHTOKEN: " + response.refresh_token, "USERID: " + response.user_id));
IdToken = response.id_token;
LocalId = response.user_id;
RefreshToken = response.refresh_token;
RefreshTokenChanged.Invoke(RefreshToken);
return new User("Anonymous", response.user_id, response.id_token);

}).Catch(error => {
Debug.Log(error.Message);
});
await Task.Delay(REQUEST_TIMEOUT);
return null;
}
public static async Task<User> SignInAnonymous() {
RestClient.Post<ExchangeRefreshTokenResponse>(currentRequest).Then(response => {
Debug.Log(("IDTOKEN: " + response.id_token, "REFRESHTOKEN: " + response.refresh_token, "USERID: " + response.user_id));
IdToken = response.id_token;
LocalId = response.user_id;
RefreshToken = response.refresh_token;
RefreshTokenChanged.Invoke(RefreshToken);
return new User("Anonymous", response.user_id, response.id_token);

}).Catch(error => {
Debug.Log(error.Message);
});
await Task.Delay(REQUEST_TIMEOUT);
return null;
}
4 Replies
Pobiega
Pobiega2y ago
I'm not familiar with RestClient but using callbacks instead of just await here seems wrong
wedman
wedman2y ago
Thanks for responding. I'm not sure if RestClient (https://github.com/proyecto26/RestClient) supports async code then. Do you recommend a library for async web requests?:)
GitHub
GitHub - proyecto26/RestClient: 🦄 A Promise based REST and HTTP cl...
🦄 A Promise based REST and HTTP client for Unity 🎮 - GitHub - proyecto26/RestClient: 🦄 A Promise based REST and HTTP client for Unity 🎮
Pobiega
Pobiega2y ago
Ah, unity... I have not written .net framework in many many years, but I'd go for HttpClient, the one that comes with .NET by default it handles async just fine
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts