Skip to content

Instantly share code, notes, and snippets.

@nosix nosix/coroutineSample.kt
Last active Sep 3, 2019

Embed
What would you like to do?
Promise and async/await sample in Kotlin/JS
fun main(args: Array<String>) {
launch {
loadAllFiles()
}
}
fun launch(block: suspend () -> Unit) {
block.startCoroutine(object : Continuation<Unit> {
override val context: CoroutineContext get() = EmptyCoroutineContext
override fun resume(value: Unit) {}
override fun resumeWithException(e: Throwable) { println("Coroutine failed: $e") }
})
}
suspend fun <T> Promise<T>.await(): T = suspendCoroutine { cont ->
then({ cont.resume(it) }, { cont.resumeWithException(it) })
}
suspend fun loadAllFiles() {
println("step1!")
openFile("https://yesno.wtf/api").await()
println("step2!")
openFile("https://yesno.wtf/api").await()
println("step2!")
openFile("https://yesno.wtf/api").await()
println("done!")
}
fun openFile(url: String): Promise<XMLHttpRequest> {
val p = Promise<XMLHttpRequest> {
resolve, reject ->
val xhr = XMLHttpRequest()
xhr.open("GET", url)
xhr.addEventListener("load", {
e ->
resolve(xhr)
})
xhr.send()
}
return p
}
// References:
// https://discuss.kotlinlang.org/t/async-await-on-the-client-javascript/2412
// https://sbfl.net/blog/2016/07/13/simplifying-async-code-with-promise-and-async-await/
@mauriciotogneri

This comment has been minimized.

Copy link

commented Jan 29, 2019

Do you know how we can accomplish the same using the new 1.3 coroutines instead of the experimental coroutines? Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.