11

I'm using the Spring Boot framework as my backend.

This is one of the calls I want to do asynchronously - it just saves a user into my mongoDB database:

@Async
public Future<Void> saveUser(String userid) {
    User user = new User();
    user.setUserId(userid);
    return new AsyncResult<Void>(mongoTemplate.save(user));
}

The method gives me an errors as mongoTemplate.save(user) returns a void value and not a Void object.

I tried to change the method by substituting in void as follows but it does not work as Future<void> and AsyncResult<void> is not accepted:

@Async
public Future<void> saveUser(String userid) {
    User user = new User();
    user.setUserId(userid);
    return new AsyncResult<void>(mongoTemplate.save(user));
}

Is there anyway to run a method that returns void in an asynchronous way on Spring?

Simon
  • 19,658
  • 27
  • 149
  • 217

3 Answers3

28

Try the following:

@Async
public void saveUser(String userid) {
    User user = new User();
    user.setUserId(userid);
    mongoTemplate.save(user);
}

Future needs to be used only when there is return type other than void.

prem kumar
  • 5,641
  • 3
  • 24
  • 36
10

The only value a Void can have is null. So all you need is

User user = new User();
user.setUserId(userid);
mongoTemplate.save(user)
return new AsyncResult<Void>(null);
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
2

Simply return

return new AsyncResult<>(null);
Ahmed Nabil
  • 17,392
  • 11
  • 61
  • 88