Why does not "await" work?
Future<void> f1() async{
Future.delayed(Duration(seconds:2), (){
print('f1');
});
}
void main() async{
print('start');
await f1();
print('end');
}
output
start
end
f1
but await
working in next code.
Future<void> f1() async{
return Future.delayed(Duration(seconds:2), (){
print('f1');
});
}
void main() async{
print('start');
await f1();
print('end');
}
output
start
f1
end
why????
I dont understand…..
3
Answers
Because in the first code block
f1()
is awaited and it’s childFuture
is not. In the second it’s returned. If you want to wait for the delayedFuture
,await
it as well. Like sobecause the in the first one, you only interupt for the
f1
,to make you better understanding see this
result:
but if you also add
await
inside thef1
, it will interupt the processresult:
in the second one, since you are returning the
Future.delayed
which mean, it direclty execute theFuture.delayed
and interupt the process.You need to either
await Future.delayed
orreturn Future.delayed
. Thef1
call in themain
expects aFuture
object to be returned which it can await.