簡體   English   中英

如何創建和完成play.libs.F.Promise?

[英]How do I create and complete a play.libs.F.Promise?

我想從調用異步第三方服務創建一個play.libs.F.Promise ,這樣我就可以鏈接調用並返回一個Promise<Result>而不是在控制器內阻塞。 像這樣的東西:

final Promise<String> promise = new Promise();
service.execute(new Handler() {
  public void onSuccess(String result) {
    promise.complete(result);
  }
})
return promise;

不幸的是,似乎沒有辦法創建一個空的play.libs.F.Promise ,也沒有方法來完成一個承諾?

假設當前版本的play和play.libs.F.Promise ,可以通過兩種方式創建promise:1)使用scala Future和Callback或2)使用play Function0 (替換任何類的A):

import static akka.dispatch.Futures.future;
//Using 1)
Promise<A> promise=Promise.wrap(future(
    new Callable<A>() {
        public A call() {
        //Do whatever
        return new A();
  }
}, Akka.system().dispatcher()));

//Using 2) - This is described in the Play 2.2.1 Documentation
// http://www.playframework.com/documentation/2.2.1/JavaAsync 
Promise<A> promise2= Promise.promise(
  new Function0<A>() {
    public A apply() {
        //Do whatever
        return new A();
    }
  }
);

編輯:當您無法修改異步塊時,因為它是由第三方提供的,您可以使用創建空Promise( scala promise ,而不是play framework promise)的方法。 然后你可以使用包含scala Promise的Future來生成一個play.libs.F.Promise,如下所示:

import akka.dispatch.Futures;

final scala.concurrent.Promise<String> promise = Futures.promise();
service.execute(new Handler() {
    public void onSuccess(String result) {
        promise.success(result);
    }
})
return Promise.wrap(promise.future());

你必須使用F.RedeemablePromise

RedeemablePromise<String> promise = RedeemablePromise.empty();

promise.map(string ->
  // This would apply once the redeemable promise succeed
  ok(string + " World!")
);

// In another thread, you now may complete the RedeemablePromise.
promise.success("Hello");

// OR you can fail the promise
promise.failure(new Exception("Problem"));

您可以通過執行以下操作返回空承諾:

return F.Promise.pure(null);

您可以像這樣創建F.Promise:

F.Promise<User> userPromise = F.Promise.promise(() -> getUserFromDb());

並在准備好時使用它的值:

userPromise.onRedeem(user -> showUserData(user));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM