Consider this example:
Future<int> doAsyncThing() => new Future.value(42);
usingAsync() async => doAsyncThing();
main() {
var thing = usingAsync();
// what is the runtimeType of thing ?
}
What is the runtimeType of the object returned by usingAsync()
? Would it be Future<Future<int>>
or Future<int>
or something else ?
An async function runs synchronously until the first await keyword. This means that within an async function body, all synchronous code before the first await keyword executes immediately.
Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. In simple terms, a future is promise to hold the result of some operation once that operation completes.
There are two different ways to execute a Future and utilize the value it returns. If it returns any whatsoever. The most well-known way is to await on the Future to return. For everything to fall into work, your function that is calling the code must be checked async.
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.
The return type of usingAsync()
is technically dynamic
because there is no return type annotation given for usingAsync()
. Omitting a return type annotation is the same as using dynamic
for the return type annotation.
The runtimeType of the object returned by usingAsync()
is Future<dynamic>
. Functions marked with async
simply always return a Future<dynamic>
object.
When the Future from usingAsync()
completes, it "flattens" its contained Future, and completes with an int
.
import 'dart:async';
Future<int> doAsyncThing() => new Future.value(42);
usingAsync() async => doAsyncThing();
main() {
var thing = usingAsync();
// what is the runtimeType of thing ?
print(thing.runtimeType); // Future
thing.then((value) {
print(value); // 42
print(value.runtimeType); // int
});
}
The author of the code sample in the original question probably wants to write:
Future<int> usingAsync() async => await doAsyncThing();
Or, even cleaner:
Future<int> usingAsync() => doAsyncThing();
That is, if your function returns a Future, you might not need to mark your function as async. Just return the Future.
See it in action: https://dartpad.dartlang.org/73fed0857efab196e3f9
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