Kotlin/kotlinx.coroutines

Make Promise.await common between k/wasm and k/js sources

Opened this issue · 6 comments

eymar commented

Use case
With kotlinx-browser:0.5.0 allowing a lot of W3C API usages being made in webMain shared source set (for both k/js and k/wasm), I'd like to have as little k/js and k/wasm specific or custom code as possible.

The Promise type is already common. Many W3C API return a Promise and it's convenient to use them in suspend functions. For example:

window.fetch(someUrl).await<Response>()

Right now I have such a snippet to simplify the code:

@OptIn(ExperimentalWasmJsInterop::class)
private suspend fun <R : JsAny?> Promise<R>.await(): R = suspendCancellableCoroutine { continuation ->
    this.then(
        onFulfilled = { continuation.resumeWith(Result.success(it)); null },
        onRejected = { continuation.resumeWithException(it.asJsException()); null }
    )
}

The Shape of the API

The API would look like the existing Promise.await but common between k/js and k/wasm. I assume a non-breaking update is possible.

Prior Art
N/A

cc: @bashor @JSMonk

The await() version that you propose isn't a full replacement for the current Promise<T>.await() on JS (EDIT: of course, Wasm/JS), as currently, the JsAny? type bound is not required.

eymar commented

The await() version that you propose isn't a full replacement for the current Promise.await() on JS, as currently, the JsAny? type bound is not required.

Got it. Then if we want it in the library out of a box, the only option is to add a function with a new name?

Not necessarily, that's a question for the JS + Wasm/JS teams. If the intention in the end is to only allow Promise values that resolve to JsAny, then the right thing to do is to deprecate the kotlinx.coroutines overloads that currently allow arbitrary Promise<T> and to move the Promise-related functions to the web source sets.

Also, do I understand correctly that JS and Wasm/JS are both experimental targets where compatibility can be broken when needed?

eymar commented

Also, do I understand correctly that JS and Wasm/JS are both experimental targets where compatibility can be broken when needed?

K/JS is stable and K/Wasm in Beta.


cc: @bashor @JSMonk tagging you folks to ask for your opinions :)

@dkhalanskyjb @bashor we need to sit together and agree on the commonized variant of the API.

I've experimented with various approaches, and I propose that we discuss this publicly instead. Here's the pull request with the option that seems most viable to me (and the list of problems standing in the way of more convenient approaches): #4563 Let's continue there!