Skip to content

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

@eymar

Description

@eymar

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions