Kotlin Kovenant中的链式承诺返回函数

Kotlin Kovenant中的链式承诺返回函数,kotlin,kovenant,Kotlin,Kovenant,我试图用Kovenant链接2个承诺返回函数,如下所示: fun promiseFunc1() : Promise<Int, Exception> { return Promise.of(1) } fun promiseFunc2() : Promise<Int, Exception> { return Promise.of(2) } fun promiseCaller() { promiseFunc1() then { it: Int -&g

我试图用Kovenant链接2个承诺返回函数,如下所示:

fun promiseFunc1() : Promise<Int, Exception> {
    return Promise.of(1)
}

fun promiseFunc2() : Promise<Int, Exception> {
    return Promise.of(2)
}

fun promiseCaller() {
    promiseFunc1() then { it: Int ->
        promiseFunc2()
    } then { it: Int ->
        // Compilation error: it is not not an integer
    }
}
    promiseFunc1() then { it: Int ->
        promiseFunc2().get()
    } then { it: Int ->
        // it is now an integer
    }
但是,由于
get()
阻塞了线程,因此只有当
然后
在后台线程上运行时,它才起作用(它是这样做的),但仍然感觉像是黑客攻击

有更好的方法吗?

当您从传递给
然后
的lambda返回另一个承诺时,您会得到
承诺
类型。因此,在下一个
中,参数
的类型是
Promise
,而不是
Int

为了平展承诺,您可以使用函数,该函数将
promise
转换为
promise
。那么您的示例如下所示:

promiseFunc1().then { it: Int ->
   promiseFunc2()
}.unwrap()
.then { it: Int ->
   // it is now an integer
}
如果
的组合{}.unwrap()
经常出现在代码中,您可以使用
kovenant functional
中的缩写:

promiseFunc1() bind { it: Int ->
   promiseFunc2()
} then { it: Int ->
   // it is now an integer
}