mike.holler
10/09/2020, 1:39 PM.js
as a npm package. I can call normal functions just fine in JS, but suspend
functions are a bit of an enigma from the .js
side. I know I can create a wrapper in jsMain
but I'd rather not manually do that for every suspend function. Is there any way to call a suspend function in JS and get a promise back (even if it requires a little helper function?)
Here is a modified version of the Base64 library example to show what I'm trying to do.
Kotlin Implementation
interface Base64Encoder {
@JsName("encode")
fun encode(src: ByteArray): ByteArray
@JsName("encodeToString")
fun encodeToString(src: ByteArray): String {
return encode(src).let { encoded ->
buildString(encoded.size) {
encoded.forEach { append(it.toChar()) }
}
}
}
suspend fun downloadAndEncodeToString(url: String): String {
return HttpClient().use {
it.get<HttpResponse>(url = Url(url)).readText()
}
}
}
JS Usage (see image below)araqnid
10/09/2020, 6:15 PM