在Play中建立复杂的承诺

时间:2012-06-07 23:22:39

标签: java asynchronous playframework playframework-1.x promise

假设我需要从我的方法返回一个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()行为一样。

2 个答案:

答案 0 :(得分:2)

我认为你想要F.Promise.map(播放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类型回调函数的参数。)

答案 1 :(得分:0)

我不确定我是否完全理解你的问题,但如果你想做一个异步的WS操作,并返回结果,这就是这样做的方法:

F.Promise<WS.HttpResponse> promise = WS.url(url).getAsync();
// The following line corresponds to your callWhenReady. 
// It waits for the result in a non blocking way.
await(promise);

WS.HttpResponse response = promise.get();

现在您可以对响应进行一些计算,并返回结果。