in JS you can turn any callback into an async () =...
# javascript
b
in JS you can turn any callback into an async () => { } callback and await stuff in it; how do you do that in Kotlin
2
t
suspend
functions, lambdas
b
how would that look with lambdas?
like a function in this shape: func("param") { }
t
Copy code
fun func(
    p: String,
    block: suspend () -> Unit,
) {
    // your code
}
b
my function definition is provided by a framework and just takes a normal function
I don't think you can do something like: func("param") suspend { }
t
async
function = function, which returns
Promise
- no magic
b
right, but I want to use an await() in there
Copy code
func("param") { 
    fetch("url").await()
}
you can do that as well in js and just work with .then() chains; but you can just plaster an async before the lambda to be able to use await:
Copy code
func("param", async () => { await fetch("url") })
t
Copy code
func("param") {
    GlobalScope.promise { 
        fetch("url")
    }
}
b
ok, so basically something similar to GlobalScope.launch in there
does that simply turn a GlobalScope.launch into a Promise type?
ah and open an async block
thank you!
t
b
looks like you'll need GlobalScope a ton in JS; do you just ignore the warnings?
or put @OptIn(DelicateCoroutinesApi::class) everywhere
t
You can create custom promise factory like this:
Copy code
fun <T> buildPromise(
    block: suspend () -> T,
): Promise<T> = 
    CoroutineScope(EmptyCoroutineContext).promise(block = block)
To avoid duplication
b
thanks, so the EmptyCoroutineContext sort of gets translated nicely to JS in this case
thank you for your continued help 🙂
🙂 2
t
async
lambda in JS will give you isolated error context. Similar task in Kotlin can be solved with isolated coroutine scope (not global). I personally don't have use cases for
GlobalScope