In Dart, if you have an async function that doesn't return anything, should it return Future<void>
or simply void
? Both seem to work, but why?
void foo() async {
print('foo');
}
Future<void> bar() async {
print('bar');
}
void main() async {
await foo();
await bar();
print('baz');
}
Compiles with no errors or warnings and prints
foo
bar
baz
Async methods that don't contain a return statement or that contain a return statement that doesn't return an operand usually have a return type of Task. Such methods return void if they run synchronously.
Event handlers naturally return void, so async methods return void so that you can have an asynchronous event handler.
The behavior of async / await is similar to combining generators and promises. Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.
In a large variety of languages void as return type is used to indicate that a function doesn't return anything. Dart allows returning null in functions with void return type but it also allow using return; without specifying any value. To have a consistent way you should not return null and only use an empty return.
In your code, both functions foo()
and bar()
are not returning anything so any function return type is valid for both functions eg:
void/T/Future<T>... foo() async {
print('foo');
}
Future<void>/T/Future<T>... bar() async {
print('bar');
}
and here,
await foo();
await bar();
await
just waits till the execution of these async functions is complete. As there is no return type, await has no purpose here(redundant) so this is and should not be a compilation error.
The difference is that Future<void>
gives you information of the execution of the function like when the execution is complete and it also allows you to specify what to do when the function is executed by using bar().then(...)
and bar().whenComplete(...)
.
While foo()
function return void
and void
does not hold as such any info like Future<void>
. If you try to await bar()
it will convert that Future
object from Future<void>
to void
.
Future
is just a container, with await
returns the values once the async "tasks" are completed. Without await
, Future
objects give you information about the execution of the function from which they are returning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With