kotlinx-browser icon indicating copy to clipboard operation
kotlinx-browser copied to clipboard

Remove the need for `null` at the end of `Promise<T>` and `GlobalEventHandlers` lambdas

Open sdeleuze opened this issue 7 months ago • 3 comments

As seen in https://github.com/wasm-outbound-http-examples/kotlin/blob/main/browser/src/wasmJsMain/kotlin/Main.kt or some Spring + Kotlin/Wasm samples I have been working on, the requirement to return null as the latest statement of some lambdas in some APIs exposed by kotlinx-browser is a significant DevXP issue as it makes the Kotlin code IMO unnecessarily ugly and can block newcomers who will not understand that requirement. For example:

fun main() {
    window.fetch("https://httpbin.org/anything").then {
        if (it.ok) {
            it.text().then {
                println(it)
                null
            }
        }
        null
    }
}

It impacts at least Promise<T> based APIs and event handlers like those defined in GlobalEventHandlers, potentially other APIs too.

It would be a big DevXP improvement if that could be fixed.

sdeleuze avatar May 19 '25 12:05 sdeleuze

Probably it will be better to use suspend fetch from Kotlin Wrappers:

suspend fun main() {
    val request = fetch("https://httpbin.org/anything")
    if (it.ok) {
        println(request.text())
    }
}

turansky avatar Aug 05 '25 02:08 turansky

Thanks for sharing this workaround, that said IMO both variants should offer a reasonable DevXP, as Coroutines footprint overhead should remain optional.

The wider issue here (does not concern only fetch API) is that the IDL to Kotlin API generator should be made more flexible to allow idiomatic Kotlin APIs.

sdeleuze avatar Aug 05 '25 14:08 sdeleuze

In this case then combines 2 operators in one (Result.map and Result.onSuccess - nearest analogs) and as result - JS payload required. Possible solution - provide additional extensions, but it doesn't look like right solution.

turansky avatar Aug 05 '25 15:08 turansky