问题描述
我正在为浏览器编写一个针对Kotlinjs的程序。我对Kotlinx的协程了解不多,但我需要它们避免将线程冻结20分钟。
if (curProduct.price?.currency !== "CAD") {
curPrice = formatPrice(
curProduct.price.text * 0.74,this.props.lang,true
);
}
在button.addEventListener中调用getBigList会导致错误suspend fun getBigList(ids: bundleID) {
val resp = GlobalScope.async{requestS("URLwithParaMS${ids}")}
val bigList = resp.await()?.let { it1 -> Json{ignoreUnkNownKeys = true}.decodeFromString<LogList>(it1) }
//do something with bigList,or return it and do something in the event listener,either way it will have to be a suspended function that makes HTTP requests based on the bigList
}
//requestS is a synchronous xmlHTTP request. wrapping synchronous with async instead of creating an async xmlHTTP request so that I can await on the response instead of using callbacks.
suspend fun main() {
val button = document.getElementById("mybutton") as HTMLButtonElement
val input = document.getElementById("myinput") as HTMLInputElement
button.addEventListener("click",{
val playerIDs = {/* data class instance derived from input.value */}
getBigList(playerIDs)
})
}
我知道为什么这样做(addEventListener不可挂起),但是我不知道如何解决(我不能只是将button.addEventListener标记为“ suspend”)
最终流程需要为:用户单击按钮-> 。程序将http请求发送到外部站点,该站点返回一个很大的列表(1000-4000),为简单起见,随机数。 -> 然后,程序获取这些返回的数字,并为每个数字发送1个新的http请求(我必须弄清楚如何对其进行速率限制)。
我仅包括这些额外信息,以便您可能拥有告诉我需要为事件侦听器做的所有信息,以及是否什至使用了正确的异步习惯用法。
解决方法
似乎您希望按钮触发一些异步活动。一种方法是:
button.addEventListener("click",{
GlobalScope.launch {
// This is a suspend lambda.
// i.e. you can call getBigList here
// The execution will suspend when needed and run until completion
}
})
这里launch
是kotlinx.coroutines
库中的function。
这类似于在JS中调用async
函数。