dart-lang / dart-lang/language
Prefix `await` is cumbersome to work with.
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
In an asynchronous Dart function, the `await expr` expression allows blocking and waiting for a future result of `expr` to complete.
This is highly convenient compared to using `Future.then`, but grammatically it's still cumbersome because await is a prefix operator with lower precedence than selectors.
Example:
```dart
var x = await (await foo.bar()).baz();
```
If you need to await an intermediate result of a longer computation chain, you need to add parentheses and go back and write the await far distanced from the operation that created the future.
If you have a cascade like:
```dart
expr
..bar()
..baz()
..qux();
```
and `baz` is (or becomes) asynchronous and you want to await it before continuing, then you have to rewrite it to something like:
```
var tmp = expr..bar();
await tmp.baz();
tmp..qux(); // or one dot, doesn't matter.
```
A solution (**proposal!**) is be to allow `.await` as a suffix operator instead of only `await ` as a prefix operator:
```dart
var x = foo.bar().await.baz().await;
expr
..bar()
..baz().await
..qux();
```
This is still only allowed inside asynchronous functions where `await` is a reserved word, so it would not be ambiguous.
It's a special syntactic form, not a named member access. An `await` is a special *kind* of selector.
You *can* do `expr?.await`, `expr..await` and `expr?..await` too. It will await (of not null), then throw away the result if it's a cascade (or follow it with more selectors, `expr..await.selectors`, and still evaluate to the original future ... but why?)
Since this is new syntax, I'd *require* the operand to have a type which implies a future type (implement `Future`, be `FutureOr`, or nullable either of those, or `dynamic` for being dynamic). No awaiting a non-future. (You can always upcast your `int` to `FutureOr` and await that, though. At least you have to be explicit about it.)
See also #1216, #2762, https://github.com/dart-lang/sdk/issues/25986, https://github.com/dart-lang/sdk/issues/23000.
(Edit, 5+ years later: Definitely with a `.` in front, not `foo() await`. Grammar is precious, `.await` is simple, updated to suggest only that.)
Contributor guide
Assessment
This issue has not been assessed yet.