【问题标题】:Kotlin/JS suspension function in an HTMLButtonElement EventListenerHTMLButtonElement EventListener 中的 Kotlin/JS 暂停功能
【发布时间】:2020-12-15 20:02:56
【问题描述】:

我正在为浏览器编写一个针对 KotlinJS 的程序。我对 Kotlinx 的协程了解不多,但我需要它们来避免线程冻结 20 分钟。

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)
    })
}

在button.addEventListener中调用getBigList会报错,Suspension functions can be called only within coroutine body 我理解它为什么这样做(addEventListener 不可暂停),但我不知道如何解决它(我不能只将 button.addEventListener 标记为 'suspend')

最后的流程需要是:用户点击按钮 -> 程序向外部站点发送 http 请求,它返回一个大的 (1000-4000) 列表,为简单起见,随机数。 -> 程序然后获取这些返回的数字并为每个数字发送 1 个新的 http 请求(我必须弄清楚如何对其进行速率限制)。

我只包含这些额外的信息,以便您可以获得所需的所有信息,告诉我我需要为事件侦听器做什么,以及我是否使用了正确的异步习惯用法。

【问题讨论】:

    标签: async-await kotlin-coroutines kotlin-js


    【解决方案1】:

    似乎您希望按钮触发一些异步活动。一种方法是:

        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 函数。

    【讨论】:

      猜你喜欢
      • 2021-01-04
      • 2017-01-08
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多