You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Dart异步函数中await执行顺序的困惑求解

Dart异步执行顺序问题解析

第一组代码执行流程(带await)

先看你贴的第一组代码:

void main() async {
  print('one');
  first();
  print('five');
}

void first() async {
  print('two');
  await second();
  print('four');
}

Future<void> second() async {
  print('three');
}

输出顺序:one → two → three → five → four

执行步骤拆解:

  1. 进入main,同步执行print('one'),输出one。
  2. 调用first(),进入first函数:
    • 同步执行print('two'),输出two。
    • 执行await second():先调用second(),second是async函数,同步执行内部的print('three'),输出three,然后返回一个已完成的Future。
    • 关键逻辑:await会暂停当前的first函数,把await后面的代码(也就是print('four'))放到微任务队列排队,随后first函数立刻返回一个Future给main,让main继续执行后续代码。
  3. main函数拿到first返回的Future后,因为没有用await等待它,直接同步执行print('five'),输出five。
  4. main函数执行完毕,Dart事件循环开始处理微任务队列,把之前暂停的print('four')拿出来执行,输出four。

第二组代码执行流程(无await)

再看去掉await的代码:

void main() async {
  print('one');
  first();
  print('five');
}

void first() async {
  print('two');
  second();
  print('four');
}

Future<void> second() async {
  print('three');
}

输出顺序:one → two → three → four → five

执行步骤:

  1. 同样先执行main里的print('one'),输出one。
  2. 调用first(),进入first函数:
    • 同步执行print('two'),输出two。
    • 调用second(),second同步执行print('three'),输出three并返回Future,但因为没有await,first函数不会暂停,直接继续执行下一行print('four'),输出four。
  3. first函数执行完返回Future给main,main继续同步执行print('five'),输出five。

核心疑问解答

加了await后print('four')没紧跟three,不是await打破了函数作用域,而是await的本质就是暂停当前async函数,将后续代码延后到微任务队列,让调用者的同步代码先执行完,等当前调用栈清空后,再处理微任务队列里的剩余代码。

简单说:await不是让整个程序等待,只是让当前的async函数暂停,把后续代码“挂起来”,先让调用它的代码继续走,等同步流程都跑完了,再回来执行挂起的部分。

内容的提问来源于stack exchange,提问作者Jun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 20:09:10