Search code examples
javascriptgowails

How to assign the value returned by a callback function to a variable? Couldn't understand from another ques. about asynchronous call


Here, I'm using the Wails for GoLang. ref: https://wails.app/

Wails helps in giving frontend to simple golang apps. In which it uses javascript, html and css to render the ui and connect frontend to backend. I am a total stranger to Javascript. So, here there is a Simple Golang Generate() that sets some string to the wails store using mystore.set("string"), which,I think, in the javascript side is some kind of callback function and calls back that string value using mystore.subscribe(). Wails has a default example for that. Where whenever any backend function generates any value and sets in the store using mystore.set(abc), it takes that store value and sets that to the span element as below.

HTML:

<span id='logo'></span>

JAVASCRIPT:

mystore.subscribe(function(state) {
    document.getElementById('logo').innerText = state;
});

Now, I want to take that value and store it to my variable, so I tried this:

var logoTitle = '';
mystore.subscribe(function(state) {
    logoTitle = state;
});

But, it's not setting that value to var logoTitle. Plus, it's saying that logoTitle variable is declared but never used. What do I do?


Solution

  • That's because that's asynchronous code. The callback in mystore.subscribe will only be called "at some point" therefore logoTitle won't be set for a while. You're basically telling mystore "once you got the value, call that function" but your code immediately continues executing the statements after it.

    If you want to run code that depends on the value passed to your callback, put that code (or a call to it) in your callback.