I'm running this code:
import 'dart:async';
void main() {
final c = Future.value(); // Other constructors and `Completer.future` all yield same results.
print(c == sync(c));
print(c == aSync(c));
}
Future sync(Future future) {
return future;
}
Future aSync(Future future) async {
return future;
}
And I get as output a seemingly strange result:
true
false
I know how futures work in Dart, and that technically we create a new Future instance for every async function, but it just seems strange how we return the same object in both cases, yet with different results.
Is this intended behaviour?
It's expected behavior. One of the things that the
asynckeyword does is to transformreturnstatements in the function body to returnFutures. If the function body already returns aFuture, don't be surprised if it gets transformed into a newFuture.What's supposed to happen is that an existing
Futuredirectly returned within anasyncfunction is implicitlyawaited. That is:is supposed to be equivalent to:
Apparently this is what's intended by the Dart language specification but isn't what happens in practice. Not having the implicit
awaitcan make error-handling confusing if theFuturefails.There also is discussion about disallowing
asyncfunctions from directly returningFutures and to require that they explicitlyawaitany returnedFutures instead.