为什么在下面的程序中异步函数在同步之前被调用?

Why in the following program Asynchronous function is being Called before Synchronous?

showAsync() {
  print('Async Function Call!!');    
}

show() async {
  await showAsync();
  print('all done!!');
}

showSync() {
  print('Sync Function Call!');
}

main(List<String> args) {
  show();
  showSync();
}

输出:

Async Function Call!!
Sync Function Call!
all done!!

showAsync函数没有做任何需要等待的事情,所以它只是执行。如果改成下面的,其他函数会先打印:

showAsync() {
  Future.delayed(Duration(seconds: 1), () {
    print('Async Function Call!!');
  });
}

正如 Günter 在评论中指出的那样:“在 Dart 1.x 中,异步函数会立即暂停执行。在 Dart 2 中,异步函数不会立即暂停,而是同步执行直到第一个 await或 return." (引自 Dart 文档)。

因此,如果您添加第二个 await showAsync(),它不会在同步调用之前执行。

这里有详细的解释:https://www.dartlang.org/tutorials/language/futures