I hope this is the right place to ask these questi...
# javascript
f
I hope this is the right place to ask these questions: 1. Are there no conversion function from any kind of
ArrayBuffer
to a Kotlin array and/or vice-versa? 2. How do you await a
Promise<S>
while blocking execution? (
let x = await f()
)
v
@2: I would use this extension function:
Copy code
suspend fun <T> Promise<T>.await() = suspendCoroutine<T> { continuation ->
  then { value -> continuation.resume(value) }

  catch { exception ->
    @Suppress("USELESS_ELVIS") // Necessary since reject can be called without parameter
    continuation.resumeWithException(exception ?: Exception("Empty promise rejection"))
  }
}
g
Not sure about the first one. But for the second you are looking for Kotlin coroutines. I'm just learning them now myself. Edit: what Valentin said
v
Edit: copied the wrong version, the snipped above is now the correct one for stable coroutines >= Kotlin 1.3
f
Thanks, pulling in all of coroutines for a js built-in is heavy...
There is no
runBlocking
and it is thus impossible to define a function as not being
suspend
. Or is there any workaround? (searching…)
I give up …
v
You can launch everywhere a new couroutine:
Copy code
fun launch(block: suspend () -> Unit) {
  async(block).catch { exception -> console.error("Failed with $exception") }
}
Copy code
fun <T> async(block: suspend () -> T): Promise<T> = Promise { resolve, reject ->
  block.startCoroutine(object : Continuation<T> {
    override fun resumeWith(result: Result<T>) {
      if (result.isSuccess) {
        resolve(result.getOrThrow())
      } else {
        reject(result.exceptionOrNull()!!)
      }
    }

    override val context: CoroutineContext get() = EmptyCoroutineContext
  })
}
f
I have an MPP project with a
fun doSomething()
and I want to have this in JS too. The
doSomething
does SHA-1, hence, I want to use
SubtleCrypto
to have a fast and proper impl.
SubtleCrypto.digest
returns a
Promise
and now I'm essentially fucked because I cannot resolve this while keeping the contract blocking for all the others.
v
Sorry, I don’t understand you
f
Let‘s say
expect fun sha1(data: ByteArray): ByteArray
is in
commonMain
. We want to have
actual fun sha1(data: ByteArray): ByteArray
in
jsMain
. We want to use https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest since it is native and tested. It returns a
Promise<ArrayBuffer>
(see https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#Return_value) which is fine in theory but impossible for us here. We cannot make an
actual suspend fun
unless we have an
expect suspend fun
, which we do not have. 😞
I'd be eternaly grateful if you can think of something. I tried various things but (as written above) gave up…