Reputation: 25974
In the following, I would expect:
This output:
Start sleep1
End sleep1
Start sleep2
End sleep2
But I get output:
Start sleep1
Start sleep2
End sleep1
End sleep2
Code:
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();
}
Also when not returning a 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();
}
Upvotes: 0
Views: 118
Reputation: 51732
Both printSleep1
and printSleep2
return Futures, so they don't necessarily start execution when you call them. (Dart 2 changes this subtly, in that they execute up to the first await, but that's not relevant here.)
Change you main to:
main() async {
await printSleep1();
await printSleep2();
}
so that printSleep2 won't get called until after printSleep1's Future completes.
Upvotes: 2