Home > database >  How to fetch data returned by a asynchronous Service in a controller (Java)
How to fetch data returned by a asynchronous Service in a controller (Java)

Time:11-16

I have a controller :

@PostMapping("/xyz")
void getThatMessageAndEmail(@RequestBody(Integer z))
{
   String messageToCatch = MG.messageGetter(z);
   System.out.println(functionToConcat(z,messageToCatch));
}

And my service messageGetter, which is an asynchronous service:

@Service
class MG()
{
    @Async
    String messageGetter(Integer z)
    {
      return "HELLOFRIEND";
    }
}

Now, I am unable to catch the message "HELLOFRIEND" in the controller. How do I catch the message in the controller (messageToCatch variable)?

CodePudding user response:

First: Async methods must be public! ;-)

Then, you have to refactor the return type to Future<String/CompletableFuture<String>:

@Async
public Future<String> messageGetter(Integer z)
// alternatively CompletableFuture<String> ...
{
  // and provide it accordingly:
  return new AsyncResult<String>("HELLOFRIEND");// or CompletableFuture.of("HELLOFRIEND");
}

In controller, you'd:

  • block async execution until return or exception:

    String messageToCatch = MG.messageGetter(z).get(); // in both cases.. 
    
  • or (do something in the mean time):

    Future<String> fut = MG.messageGetter(z);
    while (true) {
       if (fut.isDone()) { // done!
          System.out.println(functionToConcat(z, fut.get()));
          break;
       }
       // do something else
    }
    
  • Related