问题
Actually in Dart, in order to use await
in function body, one need to declare whole function as async
:
import "dart:async";
void main() async {
var x = await funcTwo();
print(x);
}
funcTwo() async {
return 42;
}
This code wouldn't work without marking main()
as async
Error: Unexpected token 'await'.
But, doc says "The await
expressions evaluates e
, and then suspends the currently running function until the result is ready–that is, until the Future has completed" (Dart Language Asynchrony Support)
So, maybe I miss something, but there is no need to force function to be asynchronous? What is a rationale for making async declaration obligatory ?
回答1:
In async
functions await
is rewritten to code where .then(...)
is used instead of await
.
The async
modifier marks such a function as one that has to be rewritten and with that await
is supported.
Without async
you would have to write
void main() {
return funcTwo().then((x) {
print(x);
});
}
This is a very simple example but the rewriting can be rather complex when more of the async features are uses, like try
/catch
, await for(...)
, ...
回答2:
One issue is that await
was not originally part of the Dart language. To maintain backward compatibility with existing programs that could potentially use await
as an identifier, the language designers added a mechanism to explicitly opt-in to using the new await
keyword: by adding a (previously invalid) construct to declare a function async
.
来源:https://stackoverflow.com/questions/54633277/await-without-declaring-function-as-async