Search code examples
promisekotlinkotlin-js-interop

How to create a Promise from the nested kotlin.js.Promise?


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?


Solution

  • 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);
        });
    });