I’ve been experiencing with some code from a previous post and the docs… but feel a bit unsure whether I’m on the right track.
The code you provided looks fine. Did you try it? Are there any problems?
Are Kotlin coroutines for Javascript ready enough to replace javascript promises?
No, they are even not meant to. Kotlin coroutines are not replacement for promises, but enhancement. You can write a similar coroutine for promises, so you’ll be able to easily create and use promises.
Here’s an example:
public fun <T> async(c: suspend () -> T): Promise<T> {
return Promise { resolve, reject ->
c.startCoroutine(object : Continuation<T> {
override fun resume(value: T) = resolve(value)
override fun resumeWithException(exception: Throwable) = reject(exception)
override val context = EmptyCoroutineContext
})
}
}
public suspend fun <T> Promise<T>.await() = suspendCoroutine<T> { c ->
then({ c.resume(it) }, { c.resumeWithException(it) })
}