await without declaring function as async

烂漫一生 提交于 2019-12-02 02:53:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!