Skip to content

Commit 7bb765f

Browse files
committed
add simple coroutine support for promises (based on proposal at Kotlin/kotlinx.coroutines#33)
1 parent 6e3267e commit 7bb765f

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package helloworld
2+
3+
import kotlin.coroutines.experimental.Continuation
4+
import kotlin.coroutines.experimental.CoroutineContext
5+
import kotlin.coroutines.experimental.EmptyCoroutineContext
6+
import kotlin.coroutines.experimental.startCoroutine
7+
import kotlin.coroutines.experimental.suspendCoroutine
8+
import kotlin.js.Promise
9+
10+
fun <T> async(block: suspend () -> T) = Promise<T> { resolve, reject ->
11+
12+
block.startCoroutine(completion = object : Continuation<T> {
13+
14+
override val context: CoroutineContext = EmptyCoroutineContext
15+
16+
override fun resume(value: T) {
17+
resolve(value)
18+
}
19+
20+
override fun resumeWithException(exception: Throwable) {
21+
reject(exception)
22+
}
23+
})
24+
}
25+
26+
fun launch(block: suspend () -> Unit) = async(block)
27+
28+
suspend fun <T> Promise<T>.await(): T = suspendCoroutine {
29+
then(it::resume).catch(it::resumeWithException)
30+
}

0 commit comments

Comments
 (0)