dart-lang / dart-lang/language
An async function declared to return FutureOr<T> can't directly return a T
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
Currently declaring an `async` function as returning `FutureOr` is allowed but seems misleading and useless (it's no different than returning `Future`) except maybe in the case of overriding a method already declared to return `FutureOr`. That is, if I have:
```dart
FutureOr foo() async {
return 42;
}
```
then `foo() is Future` is true and and `foo() is int` is not, and the only way to extract the value is via `await`/`then()`.
## Motivation:
I want to have a function:
```dart
FutureOr foo(bool doOptionalWork) async {
// ... Do some preliminary work here...
if (doOptionalWork) {
await someAsyncOperation();
}
// ... Do some additional work here...
return result;
}
```
with the expectation that calling `foo(false)` will return an `int`. (The intent is avoid forcing `await`/`then()` onto the caller.)
A workaround is to transform the code to avoid using `async`:
```dart
FutureOr foo(bool doOptionalWork) {
// ... Do some preliminary work here...
int doAdditionalWork() {
// ... Do some additional work here...
return result;
}
if (doOptionalWork) {
return someAsyncOperation().then((_) {
return doAdditionalWork();
});
}
return doAdditionalWork();
}
```
Could the compiler do such a transformation automatically?
Contributor guide
Research direction
Read the examples comparing an async FutureOr function with the non-async workaround, then review the issue discussion for constraints on overriding methods. A complete result would decide whether the compiler should transform this pattern and specify the resulting return behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- dart
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100