我想恢复我的承诺并从中返回delegate.call(context),但我只能返回SimpleResult。
public class Authenticate extends Action<Authentication> {
@Override
public Promise<SimpleResult> call(final Context context) throws Throwable {
WSRequestHolder holder = WS.url(...);
final Promise<Response> promise = holder.get();
Promise<SimpleResult> result = promise.flatMap(new Function<Response, Promise<SimpleResult>>() {
@Override
public Promise<SimpleResult> apply(Response response) throws Throwable {
JsonNode user = response.asJson().path("response");
context.args.put("user", user);
return delegate.call(context);
}
}).recover(new Function<Throwable, SimpleResult>() {
@Override
public SimpleResult apply(Throwable e) {
/* cant return delegate.call(context); from here */
return redirect(routes.Application.index());
}
});
return result;
}
}
在方法调用之前,可能还有其他标准和更好的方法来存储userinfo吗?
答案 0 :(得分:5)
您发布的解决方案不是一个好的解决方案,在进行异步编程时,您永远不应该使用Await.result,否则可能会导致死锁和大量性能问题。
我们需要在Play promise API中添加recoverWith
方法,但在此之前,您可以这样做(为简洁起见使用JDK8语法):
public class Authenticate extends Action<Authentication> {
public Promise<SimpleResult> call(final Context context) throws Throwable {
Promise<SimpleResult> result = WS.url(...).get();
Promise<SimpleResult> result = promise.flatMap( response -> {
JsonNode user = response.asJson().path("response");
context.args.put("user", user);
return delegate.call(context);
}).map(Promise::pure).recover( e -> {
return delegate.call(ontext)(routes.Application.index());
}).flatMap(a -> a);
return result;
}
}
基本上,上面通过与Promise<SimpleResult>
的映射将Promise<Promise<SimpleResult>>
展开为Promise::pure
,然后您可以恢复返回Promise<SimpleResult>
,然后通过以下方式平衡承诺的承诺flatMapping with identity function。
答案 1 :(得分:0)
我解决了这个问题:
WSRequestHolder holder = WS.url(...)
final Promise<Response> userPromise = holder.get();
Promise<SimpleResult> result = Promise.promise(new Function0<Response>() {
@Override
public Response apply() throws Throwable {
Timeout timeout = new Timeout(2000);
Future<Response> future = userPromise.wrapped();
Response response = Await.result(future, timeout.duration());
return response;
}
}).flatMap(new Function<Response, Promise<SimpleResult>>() {
@Override
public Promise<SimpleResult> apply(Response response) throws Throwable {
try {
JsonNode userInfo = response.asJson();
context.args.put("user", userInfo);
} catch(Exception ex) {
}
return delegate.call(context);
}
});
return result;