https://kotlinlang.org logo
m

mike.holler

10/09/2020, 1:39 PM
I have a Kotlin Multiplatform library I'm trying to use from
.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
Copy code
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)
a

araqnid

10/09/2020, 6:15 PM
It seems like you basically want to do whatever kotlinx.coroutines.promise does - if you can simply call that, that’s easiest. Otherwise, you basically need to call the suspend function with a continuation that will call resolve/reject and “false” as the suspended flag.
2 Views