gpt4 book ai didi

kotlin - Kovenant中的链接许诺返回函数

转载 作者:行者123 更新时间:2023-12-02 13:24:29 26 4
gpt4 key购买 nike

我试图将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中的 then按原样返回该值。如何从 promiseFunc2获取实际的整数?我得到的唯一解决方案是使用 get()函数,如下所示:
    promiseFunc1() then { it: Int ->
promiseFunc2().get()
} then { it: Int ->
// it is now an integer
}

但是,由于 get()阻塞了线程,因此仅当 then在后台线程上运行时它才起作用(确实如此),这仍然感觉像是黑客。

有没有更好的办法?

最佳答案

当您从传递给Promise<Promise<Int, Exception>, Exception>的lambda返回另一个 promise 时,将获得then类型。因此,在下一个then中,参数it的类型为Promise<Int,...>而不是Int

为了兑现 promise ,您可以使用 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
}

关于kotlin - Kovenant中的链接许诺返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42609590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com