英文:
How to assign the value returned by a callback function to a variable? Couldn't understand from another ques. about asynchronous call
问题
这里,我正在使用Wails来进行GoLang开发。
参考链接:https://wails.app/
Wails可以帮助我们为简单的GoLang应用程序提供前端界面。它使用JavaScript、HTML和CSS来渲染UI并连接前端与后端。我对JavaScript完全陌生。在这里,有一个简单的Golang Generate()函数,它使用mystore.set("string")将一些字符串设置到Wails存储中。我认为,在JavaScript端,mystore.set("string")是一种回调函数,并使用mystore.subscribe()回调该字符串值。
Wails有一个默认的示例。每当后端函数生成任何值并使用mystore.set(abc)将其设置到存储中时,它会获取该存储值并将其设置到下面的span元素中。
HTML:
<span id='logo'></span>
JavaScript:
mystore.subscribe(function(state) {
document.getElementById('logo').innerText = state;
});
现在,我想将该值存储到我的变量中,所以我尝试了以下代码:
var logoTitle = '';
mystore.subscribe(function(state) {
logoTitle = state;
});
但是,它没有将该值设置到logoTitle变量中。而且,它还说logoTitle变量已声明但从未使用过。
我该怎么办?
英文:
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?
答案1
得分: 1
这是因为这是异步代码。在mystore.subscribe
的回调函数中,只会在某个时间点被调用,因此logoTitle
不会立即设置。你基本上是在告诉mystore
:“一旦你得到了值,就调用那个函数”,但是你的代码立即继续执行它后面的语句。
如果你想运行依赖于回调函数传递的值的代码,请将该代码(或对其的调用)放在回调函数中。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论