2

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?

holi-java
  • 29,655
  • 7
  • 72
  • 83
user3706629
  • 209
  • 2
  • 9

2 Answers2

2

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);
    });
});
holi-java
  • 29,655
  • 7
  • 72
  • 83
1
fun c(): Promise<Int> {
    return a().then ({
        b().unsafeCast<Int>() 
        //Result of b is Promise<Int>, not Int, but then has bad type declaration
    })
}
user3706629
  • 209
  • 2
  • 9
  • 1
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Donald Duck Jun 17 '17 at 10:22
  • This is actually useful in certain situations. Basically in JS you can return a promise as a result of a promise, but in Kotlin the typings are screwed up since forever. – LppEdd Jun 24 '23 at 12:21