跳到正文
教程首页
DartCH 05ch05_async

ch05-async

Dart 异步:Future、async/await、Stream、异步错误处理。完整工程共 7 个文件,其中 7 个文本源文件可在下面在线阅读。

7

在线文本文件

1,002

源码行数

dart / yaml / text

语言

12 KB

打包体积

在线阅读源码

左侧按目录浏览,点击文件切换。右上角可复制代码、复制路径或单独下载文件。在线视图只覆盖文本源码,完整工程请下载 zip。

darttextyaml

7 text files · 1,002 lines

dartlib/futures.dart
/// `Future` 与 `async`/`await`:Dart 的"单线程并发"。
///
/// 关键心智:
/// - `Future<T>` 不是线程,只是一个**将来会有值(或错误)的容器**;它注册回调,不启动并发。
/// - `await` 不阻塞线程,只把当前函数后半段变成回调,让出事件循环。
/// - 所以 Dart 里 `await` 期间别的任务照样跑;但没有多核并行(并行要用 isolate,ch08)。
///
/// 对照 Go:goroutine 是抢占式调度的真线程(M:N),`go f()` 立刻并行;
///          Dart 里 `f()` 只是入队一个微任务,永远在当前 isolate 的线程上跑。
/// 对照 C:Future 相当于"回调 + 状态机",手写在 C 里就是一堆函数指针和 enum state。
library;

import 'dart:async';

/// 模拟一次 I/O:延时后返回 `x * 2`。
Future<int> fetchValue(int x) =>
    Future<int>.delayed(const Duration(milliseconds: 100), () => x * 2);

/// 串行:三个 await 依次执行,总耗时 = 三者之和。
Future<int> sumSequential() async {
  final a = await fetchValue(1); // 100ms
  final b = await fetchValue(2); // +100ms
  final c = await fetchValue(3); // +100ms
  return a + b + c;
}

/// 并发:`Future.wait` 同时启动三个 Future,总耗时 = 最慢的那个。
Future<int> sumConcurrent() async {
  final results = await Future.wait<int>(<Future<int>>[
    fetchValue(1),
    fetchValue(2),
    fetchValue(3),
  ]);
  return results.reduce((int a, int b) => a + b);
}

/// `Future.wait` 默认 `eagerError: false`:等所有 Future 结束后再抛第一个错误。
/// `eagerError: true`:第一个错误立刻抛出,但其余 Future 仍在跑(不会被取消!)。
Future<List<int>> waitWithError(bool eager) => Future.wait<int>(
      <Future<int>>[
        Future<int>.delayed(const Duration(milliseconds: 10), () => 1),
        Future<int>.delayed(
          const Duration(milliseconds: 20),
          () => throw StateError('第二项失败'),
        ),
        Future<int>.delayed(const Duration(milliseconds: 30), () => 3),
      ],
      eagerError: eager,
    );

/// `Future.any`:第一个完成的赢,其余被忽略(同样不会被取消)。
Future<int> fastest() => Future.any<int>(<Future<int>>[
      Future<int>.delayed(const Duration(milliseconds: 30), () => 1),
      Future<int>.delayed(const Duration(milliseconds: 10), () => 2),
      Future<int>.delayed(const Duration(milliseconds: 20), () => 3),
    ]);

/// 错误处理:`try/catch` 能捕获 `await` 的异常,等价 Go 的 `err != nil` 检查,
/// 但**不需要每步都写**——异常会穿过整条 async 调用链。
Future<int> failing() async {
  await Future<void>.delayed(const Duration(milliseconds: 10));
  throw StateError('后端返回 500');
}

/// 兜底:只捕获指定类型,其余继续向上抛(比 Go 的 `if err != nil { return err }` 更精细)。
Future<int> recovered() async {
  try {
    return await failing();
  } on StateError catch (e) {
    // ignore: avoid_print
    return e.message.length; // 模拟"降级到缓存"
  }
}

/// `onError` 回调式写法:老代码和不方便用 `await` 的地方(如 `then` 链)会用到。
Future<int> recoveredWithCallback() =>
    failing().then((int v) => v).catchError((Object e) => -1);

/// 超时:`Future.timeout` 会抛 `TimeoutException`,除非给了 `onTimeout`。
Future<int> slowWithTimeout() => Future<int>.delayed(
      const Duration(seconds: 5),
      () => 42,
    ).timeout(
      const Duration(milliseconds: 100),
      onTimeout: () => -1,
    );

/// 超时不兜底 → 抛 `TimeoutException`。
Future<int> slowWithoutFallback() =>
    Future<int>.delayed(const Duration(seconds: 5), () => 42)
        .timeout(const Duration(milliseconds: 100));

/// "发射后不管":显式用 `unawaited` 表明"我知道它可能失败,但我不等"。
/// 不写 `unawaited` 编译器不会报错,但**未捕获的异步错误会让整个 isolate 崩溃**。
void fireAndForget(List<String> log) {
  unawaited(
    Future<void>.delayed(const Duration(milliseconds: 10), () => log.add('done')),
  );
}

/// 微任务 vs 事件队列的执行顺序(详见 event_loop.dart)。
Future<List<String>> scheduledOrder() async {
  final log = <String>[];
  log.add('sync-1');
  scheduleMicrotask(() => log.add('microtask'));
  Timer(Duration.zero, () => log.add('timer'));
  unawaited(Future<void>(() => log.add('future')));
  unawaited(Future<void>.microtask(() => log.add('future.microtask')));
  log.add('sync-2');
  // 两轮事件循环足以排空上面所有任务
  await Future<void>.delayed(Duration.zero);
  await Future<void>.delayed(Duration.zero);
  return log;
}

代码构成:dart 19 KB · text 12 KB · yaml 394 B

本地运行

zip → 解压 → 执行
$cd examples/ch05-async && dart pub get && dart run

这个 zip 里有什么

  • • 完整工程目录(含 Android / iOS / 桌面平台脚手架)
  • • lib / bin / test / native 全部源码与测试
  • • pubspec.yaml、锁文件与平台配置文件
  • • 已排除 .dart_tool / build / target / ephemeral 等构建产物

已验证

  • dart analyze 0 告警、dart test 19 个用例全绿(用 fake_async 虚拟时钟,不 sleep)
查看全部示例