我是KotlinJs的新手,我想检查一下它在无服务器服务开发中的潜力。
我决定首先使用 KotlinJs 文档中建议的dynamic
,以使用HTTP GET调用外部API 方法。但是,如果没有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()
}
机制,我将无法提出使用它的任何方式。
thread_info
当然,这个示例可以很好地工作,但是我觉得它必须是不禁用Kotlin的类型检查器的更好方法。
答案 0 :(得分: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)
}
希望它将对以后的人有所帮助。