A.A
A.A

Reputation: 4091

Dart async void

Why we can have void myFunc() async{} function? Why void returning is acceptable Actually every async is a Future and I except the Future<void> returning value

Upvotes: 1

Views: 83

Answers (1)

lrn
lrn

Reputation: 71623

For the same reason:

void log(String message) {
  getLogger.then((logger) {
    logger.write(message);
  });
}

would be allowed. It does something asynchronous, but doesn't return a future.

Sometimes you just want to do something which involves waiting for an asynchronous function, while not actually needing, or wanting, anyone to wait for you.

I'd be happier if void foo() async { ... } didn't return a future at all, but as it is, a void function may return any value, it's the caller's responsibility not to use that value for anything. That's what a void return type means.

The biggest issue with a void return type on an async function is that it might hide an easily made mistake. If the author intended to return a Future<void>, and just forgot to write the Future, then it won't be caught locally. You won't notice it until someone tries to do an await on the returned value and gets a warning about using the value of a void expression. So, do be careful.

Upvotes: 2

Related Questions