为什么等待不等

时间:2018-05-27 12:38:38

标签: dart

在下文中,我希望:

此输出:

Start sleep1
End sleep1
Start sleep2
End sleep2

但我得到了输出:

Start sleep1
Start sleep2
End sleep1
End sleep2

代码:

Future printSleep1() async{
  print('Start sleep1');
  return await new Future.delayed(const Duration(seconds: 1), () => print('End sleep1'));
}

Future printSleep2() async{
  print('Start sleep2');
  return new Future.delayed(const Duration(seconds: 1), () => print('End sleep2'));
}

main() {
    printSleep1();
  printSleep2();
}

同时未退回Future

printSleep1() async{
  print('Start sleep1');
  await new Future.delayed(const Duration(seconds: 1), () => print('End sleep1'));
}

printSleep2() async{
  print('Start sleep2');
  new Future.delayed(const Duration(seconds: 1), () => print('End sleep2'));
}

main() {
    printSleep1();
  printSleep2();
}

1 个答案:

答案 0 :(得分:2)

printSleep2main() async { await printSleep1(); await printSleep2(); } 都返回Futures,所以当你调用它们时它们不一定会开始执行。 (飞镖2巧妙地改变了这一点,因为它们执行到第一次等待,但这与此无关。)

将您改为:

{{1}}

这样在printSleep1的Future完成之后才会调用printSleep2。