Search code examples
asynchronousdartlanguage-design

await without declaring function as async


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 ?


Solution

  • 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(...), ...