Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when I return a Future from a function marked as async in Dart?

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 ?

like image 306
Seth Ladd Avatar asked Oct 10 '15 15:10

Seth Ladd


People also ask

What does async do in Dart?

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.

Is Future asynchronous?

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.

How do you return the future object in Flutter?

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.

Does async automatically return promise?

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.


1 Answers

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

like image 106
Seth Ladd Avatar answered Sep 29 '22 04:09

Seth Ladd