Skip to content

Incorrect behavior of return in async function. #39204

Closed
@lrhn

Description

@lrhn

The Dart 2 behavior for returns in async functions is to await a future if it's a future of the flattened return type.

That is:

Future<int> foo() { 
   return someExpression;
}

will evaluate someExpression with context type FutureOr<int>, and if it is a Future<int>, it is awaited before returning its value.

That it's awaited and not passed directly to a completer (an implementation detail) is important in the case where the return is inside a try/catch an you try to return a future containing an error.

Example:

Future<int> foo() {
   try {
     return compute();
   } catch (e) {
     return -1;
   }
}
Future<int> compute() async { 
  throw "No";
}
main() {
 foo().then(print);  // should print -1
}

See #22730 for history of the spec change.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions