3

I have a Javascript function which should (does) return a string. The issue is that the C# part is always null although I've verified the JS function IS returning a string.

Here's the Javascript function:

window.get_current_user = () => {
        Moralis.User.currentAsync().then(function (user) {
            var wallet = user.get('ethAddress');
            return wallet;
        });
    }

Here's the C# calling it

 private async void GetAddress()
 {
    var userAddress = await _js.InvokeAsync<string>("get_current_user");
    _js.InvokeVoidAsync("alert", userAddress);
 }

I've used the Chrome Dev Console dev tools to breakpoint at the line in which it returns the value and verified the value is correct and a string. enter image description here

I've also placed a breakpoint on the 4th line of the GetAddress function and see that the value of 'userAddress' is indeed null

enter image description here

AcePilot10
  • 178
  • 1
  • 12
  • 4
    In the dev console - try executing your function - `window.get_current_user()`. Does that return something? Do you need a `return` in front of `Moralis...`? – jimnkey Apr 27 '22 at 19:35
  • 1
    @jimnkey That's what it was! I forgot the return in front of the initial call. Thank you so much! If you want to answer the question I'll mark it. – AcePilot10 Apr 27 '22 at 19:41
  • 1
    That's ok. Just glad I could help! – jimnkey Apr 27 '22 at 19:56
  • 3
    Also, don't use `async void` here. Make it `async Task` (and await it). – H H Apr 27 '22 at 20:35

1 Answers1

2

Do the following, the return should be outside of the second function:

window.get_current_user = () => {
var wallet = null;
        Moralis.User.currentAsync().then(function (user) {
            wallet = user.get('ethAddress');
            
        });
return wallet;
    }
Dharman
  • 30,962
  • 25
  • 85
  • 135
JS Interop
  • 21
  • 3