How to create and complete play.libs.F.Promise?

I would like to create play.libs.F.Promisefrom a call to a third-party async service so that I can bind the call and return Promise<Result>instead of locking inside the controller. Something like that:

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

Unfortunately, there is no way to create an empty one play.libs.F.Promise, and no way to fulfill a promise:

+3
source share
4 answers

You must use 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"));
+1
source

, play.libs.F.Promise, : 1) a scala Future and 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();
    }
  }
);

: , , (scala , ). , scala Promise, 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());
+1

, :

return F.Promise.pure(null);
0

F.Promise :

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

, :

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

All Articles