Kotlin Kovenant中的链式承诺返回函数
我试图用Kovenant链接2个承诺返回函数,如下所示: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
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
}