我是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的类型检查器。
我找到了一种不使用动态回调的方法,就像在经典的.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)
}
希望它能帮助将来的某个人。