【问题标题】:Why in the following program Asynchronous function is being Called before Synchronous?为什么在以下程序中异步函数在同步之前被调用?
【发布时间】:2018-12-23 21:35:37
【问题描述】:
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!!

【问题讨论】:

    标签: asynchronous dart async-await dart-pub


    【解决方案1】:

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

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

    正如 Günter 在 cmets 中指出的那样:“在 Dart 1.x 中,异步函数立即暂停执行。在 Dart 2 中,异步函数不是立即暂停,而是同步执行,直到第一次等待或返回。"(引自 Dart 文档)。

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

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

    【讨论】:

    • 对。在 Dart 2 中,异步函数开头的同步部分被同步执行。
    • @GünterZöchbauer 谢谢,我在答案中添加了一些信息。
    猜你喜欢
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    • 2012-07-22
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 2020-12-20
    相关资源
    最近更新 更多