KotlinJs - 没有动态类型功能的简单HTTP GET

问题描述 投票:0回答:1

我是KotlinJs的新手,我想检查它在无服务器服务开发方面的潜力。

我决定首先使用KotlinJs文档中建议的XMLHttpRequest()使用HTTP GET方法调用外部API。但是,如果没有dynamic机制,我无法想出任何使用它的方法。

fun main(args: Array<String>) {

    val url = "https://jsonplaceholder.typicode.com/todos/1"

    var xhttp: dynamic = XMLHttpRequest()
    xhttp.open("GET", url, true)
    xhttp.onreadystatechange = fun() {
        if (xhttp.readyState == 4) {
            println(xhttp.responseJson)
        }
    }
    xhttp.send()
}

当然这个例子工作得非常好,但我觉得必须更好地做到这一点而不禁用Kotlin的类型检查器。

  • 有没有办法只使用KotlinJs(没有动态)?
  • 如果不可能,有人至少可以解释原因吗?
http-get kotlin-js
1个回答
0
投票

我找到了一种不使用动态回调的方法,就像在经典的.js中一样

private fun getData(input: String, callback: (String) -> Unit) {

    val url = "https://jsonplaceholder.typicode.com/todos/$input"
    val xmlHttp = XMLHttpRequest()
    xmlHttp.open("GET", url)
    xmlHttp.onload = {
        if (xmlHttp.readyState == 4.toShort() && xmlHttp.status == 200.toShort()) {
            callback.invoke(xmlHttp.responseText)
        }
    }
    xmlHttp.send()
}

而不只是称之为:

getData("1") {
    response -> println(response)
}

希望它能帮助将来的某个人。

© www.soinside.com 2019 - 2024. All rights reserved.