Skip to content

Instantly share code, notes, and snippets.

@nosix
Last active February 13, 2023 18:14
Show Gist options
  • Save nosix/5994e53d5bef20292b998d6690649dc1 to your computer and use it in GitHub Desktop.
Save nosix/5994e53d5bef20292b998d6690649dc1 to your computer and use it in GitHub Desktop.
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
Copy link

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