Question

Is there a way to have an Action which can return either a Result or a Promise<Result>?

The scenario is that based on the request (parameters and headers) the action decides if to return a simple Result or it needs to make a http request to another service and only then return the result, and so to use Promise<Result>.

routes:

GET /dosomething    controllers.MyController.doSomething()

java:

public static Result doSomething() {
    Request request = request();

    if (...) {
        return getData();
    } else {
        return ok(...);
    }
}

private static Promise<Result> getData() {
    ...
}

The problem is that if the Action returns one (in it's signature) then I can't return the other...

Any ideas on how to go about this?

Was it helpful?

Solution

As mentioned in the comment, the easiest would be to always return a Promise, and wrap non-async actions with a completed Promise. To wrap a value in a completed promise, simply use the static pure method:

public static Promise<Result> doSomethingAsync() {
  if (...) {
    return getData();
  } else {
    return F.Promise.pure(ok(...));
  }
}

OTHER TIPS

This is far from being an optimal solution but it seems to do the trick, and I'm adding it as an answer in case others will look for a solution in the future.
If you have another idea of how to handle this situation I'd love to know!

Based on the advise made by @MariusSoutier I created this method:

public static F.Promise<Result> wrapResultAsPromise(final Result result) {
    return F.Promise.promise(
        new F.Function0<Result>() {
            public Result apply() {
                return result;
            }
        }
    );
}

Then if an Action has a scenario for which it needs to return a promise then all returned results are wrapped up as promises.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top