Skip to content

Instantly share code, notes, and snippets.

@ichenhe
Last active November 23, 2022 10:59
Show Gist options
  • Save ichenhe/e2e7156defd25eef4378fa265d3224a2 to your computer and use it in GitHub Desktop.
Save ichenhe/e2e7156defd25eef4378fa265d3224a2 to your computer and use it in GitHub Desktop.
Using Kotlin to implemant Promise (js) style coroutine. 用 Kotlin 实现 Promise (js) 风格的协程 API
import kotlin.concurrent.thread
import kotlin.coroutines.*
typealias Callback<T> = (T) -> Unit
class Promise<T>(private val run: (Callback<T>) -> Unit) {
fun then(callback: Callback<T>) {
run(callback)
}
}
fun heavyJob(): Promise<String> {
return Promise { callback ->
thread {
Thread.sleep(2000)
callback("slow")
}
}
}
@RestrictsSuspension
interface AsyncScope {
suspend fun <T> await(block: () -> Promise<T>): T
}
fun async(block: suspend AsyncScope.() -> Unit) {
val completion = Async()
block.startCoroutine(completion, completion)
}
class Async : Continuation<Unit>, AsyncScope {
override val context: CoroutineContext
get() = EmptyCoroutineContext
override fun resumeWith(result: Result<Unit>) {
result.getOrThrow()
}
override suspend fun <T> await(block: () -> Promise<T>): T = suspendCoroutine { continuation ->
block().then { result ->
continuation.resume(result)
}
}
}
fun asyncCall() {
async {
val r = await { heavyJob() }
println(r)
}
}
fun main() {
asyncCall()
println("first")
}
@ichenhe
Copy link
Author

ichenhe commented Nov 23, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment