Chaining承诺在Kovenant中返回职能
我试图连锁2承诺与Kovenant功能,如下所示:
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 } }
Kovenant似乎回报了价值。 我如何从promiseFunc2
得到实际的整数? 我得到的唯一解决方案是使用get()
函数,如下所示:
promiseFunc1() then { it: Int -> promiseFunc2().get() } then { it: Int -> // it is now an integer }
但是,由于get()
阻塞了线程,所以只有在后台线程上运行时才能工作,但是它仍然是一种黑客攻击。
有没有更好的办法?
当你从传递给lambda的lambda返回另一个promise时Promise<Promise<Int, Exception>, Exception>
你得到Promise<Promise<Int, Exception>, Exception>
类型。 因此,在接下来的参数中, it
具有类型Promise<Int,...>
而不是Int
。
为了保证承诺,你可以使用unwrap
函数,将Promise<Promise<V>>
转换为Promise<V>
。 那么你的例子看起来像:
promiseFunc1().then { it: Int -> promiseFunc2() }.unwrap() .then { it: Int -> // it is now an integer }
如果那个then {}.unwrap()
组合经常出现在你的代码中,你可以使用它的速记bind
从kovenant-functional
:
promiseFunc1() bind { it: Int -> promiseFunc2() } then { it: Int -> // it is now an integer }