-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2-promisify.kt
More file actions
38 lines (33 loc) · 1.09 KB
/
2-promisify.kt
File metadata and controls
38 lines (33 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package AsyncAdapter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
// Callback-last function to Promise-returning
fun <T, K>promisify(scope: CoroutineScope = GlobalScope, fn: (data: T, Errback<K>) -> Unit) = { arg: T ->
var res: K? = null
scope.async {
fn(arg) { error, data ->
if (error != null) throw error
res = data
}
res
}
}
// Usage
private fun twiceCallback(x: Int, callback: Errback<Int>) = callback(null, x * 2)
private val twicePromise = promisify(fn=::twiceCallback)
private fun halfCallback(x: Int, callback: Errback<Int>) = callback(null, x / 2)
private val halfPromise = promisify<Int, Int> { data, cb -> halfCallback(data, cb) }
private fun main() {
twiceCallback(100) { _, value ->
halfCallback(value!!) { _, result ->
println("callbackLast: $result")
}
}
runBlocking {
val a = twicePromise(100).await()
val b = halfPromise(a!!).await()
println("promisified: $b")
}
}