kotlin.js.Promise
has function then
with this declaration:
open fun <S> then(
onFulfilled: (T) -> S,
onRejected: (Throwable) -> S = definedExternally
): Promise<S>
I have two functions a()
and b()
. They both return a Promise<Int>
. (They represent some requests to the server.) I need to combine them and create a new function like:
fun c(): Promise<Int> {
a().then({
b()
})
}
But it is not possible, because return type is Promise<Promise<Int>>
and not Promise<Int>
.
I think this is possible in Javascript. How can I chain promises in Kotlin?
you need an additional Promise
for that, for example:
fun c(): Promise<Int> {
return Promise({ resolve, reject ->
a().then({
b().then(resolve, reject);
});
})
}
the code above also can simplified by using single-expression function as below:
fun c() = Promise({ resolve, reject ->
a().then({
b().then(resolve, reject);
});
});