等待而不将函数声明为异步

await without declaring function as async

实际上在 Dart 中,为了在函数体中使用 await,需要将整个函数声明为 async:

import "dart:async";

void main()  async {
  var x = await funcTwo();
  print(x);  
}

funcTwo() async {
  return 42;
}

如果不将 main() 标记为 async,此代码将无法运行

Error: Unexpected token 'await'. 

但是,医生说 "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)

所以,也许我错过了什么,但没有必要强制函数异步?强制执行异步声明的理由是什么?

async 函数中 await 被重写为使用 .then(...) 而不是 await 的代码。

async 修饰符将这样的函数标记为必须重写的函数,因此支持 await

没有 async 你将不得不写

void main() {
  return funcTwo().then((x) {
    print(x);  
  });
}

这是一个非常简单的示例,但是当使用更多异步功能时,重写可能会相当复杂,例如 try/catchawait for(...)、...

一个问题是 await 最初并不是 Dart 语言的一部分。为了保持与可能使用 await 作为标识符的现有程序的向后兼容性,语言设计者添加了一种机制来明确选择使用新的 await 关键字:通过添加(以前无效的)构造声明一个函数 async.