What happens when I return the future from a function marked async in Dart?

Consider the following 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 usingAsync()? Will it be Future<Future<int>>or Future<int>or something else?

+4
source share
1 answer

The return type is usingAsync()technically dynamicbecause for usingAsync()there is no annotation of the return type. Omitting a return type annotation is similar to using a dynamicreturn value type annotation.

The runtime of the object returned usingAsync()is Future<dynamic>. Functions marked asyncsimply always return an object Future<dynamic>.

usingAsync() , "" "" 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
  });
}

, , :

Future<int> usingAsync() async => await doAsyncThing();

, :

Future<int> usingAsync() => doAsyncThing();

, , async. .

: https://dartpad.dartlang.org/73fed0857efab196e3f9

+4

Source: https://habr.com/ru/post/1611101/


All Articles