处理 Futures

  • async 和 await 搭配使用
  1. Future checkVersion() async {
  2. var version = await lookUpVersion();
  3. // Do something with version
  4. }
  • 使用 try catch
  1. try {
  2. version = await lookUpVersion();
  3. } catch (e) {
  4. // React to inability to look up the version
  5. }
  • 可以在一个 async 函数中多次使用 await
  1. var entrypoint = await findEntrypoint();
  2. var exitCode = await runExecutable(entrypoint, args);
  3. await flushThenExit(exitCode);

声明 async 函数

  1. // 同步函数
  2. String lookUpVersion() => '1.0.0';
  3. // 异步函数
  4. Future<String> lookUpVersion() async => '1.0.0';

处理 Streams

  • 异步循环
  1. await for (varOrType identifier in expression) {
  2. // Executes each time the stream emits a value.
  3. }
  • await for 必须在 async 的函数体中
  1. Future main() async {
  2. // ...
  3. await for (var request in requestServer) {
  4. handleRequest(request);
  5. }
  6. // ...
  7. }