gpt4 book ai didi

java - 在 Play 中构建复杂的 Promise

转载 作者:行者123 更新时间:2023-12-02 07:45:29 25 4
gpt4 key购买 nike

假设我需要从我的方法返回一个 promise ,这取决于外部资源和一些计算。我想象的是这样的:

Promise<Integer> foo() {
return WS.url(url)
.getAsync()
.callWhenReady(new Function<HttpResponse>(){
Integer parse(HttpResponse response) {
// parsing business logic
// ...
int parsed = ...;
return parsed;
}
});
}

callWhenReady 可以使用什么?这本质上就像 jQuery.promise() 的行为。

最佳答案

我想你想要F.Promise.map( Play 2.0.2):

    /**
* Maps this promise to a promise of type <code>B</code>. The function <code>function</code> is applied as
* soon as the promise is redeemed.
*
* Exceptions thrown by <code>function</code> will be wrapped in {@link java.lang.RuntimeException}, unless
* they are <code>RuntimeException</code>'s themselves.
*
* @param function The function to map <code>A</code> to <code>B</code>.
* @return A wrapped promise that maps the type from <code>A</code> to <code>B</code>.
*/
public <B> Promise<B> map(final Function<A, B> function) {
return new Promise<B>(
promise.map(new scala.runtime.AbstractFunction1<A,B>() {
public B apply(A a) {
try {
return function.apply(a);
} catch (RuntimeException e) {
throw e;
} catch(Throwable t) {
throw new RuntimeException(t);
}
}
})
);
}

从您的代码看来,您正在使用早期版本的 Play,但我认为您仍然应该能够将 callWhenReady 替换为 map (并添加一个回调函数的 Integer 类型参数)。

关于java - 在 Play 中构建复杂的 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10941206/

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