Reputation: 3299
I am trying to understand how Dart performs async calls.
Given the following code:
main() {
test("test", () async{
await myCall( );
print( "done");
});
}
Future myCall( ) async{
["0","1","2"].forEach( (item) async{
print( "about to callback");
await futurePrint( item);
print( "done callback");
});
print( "done mycall");
return new Future.value();
}
Future futurePrint( String str){
print( "string = ${str}");
return new Future.value();
}
I would expect the output to be
about to future print
string = 0
done future print
about to future print
string = 1
done future print
about to future print
string = 2
done future print
done mycall
done
But the code actual output is
print( "done mycall");
about to future print
string = 0
about to future print
string = 1
about to future print
string = 2
done
done future print
done future print
done future print
Why does the 'done myCall' occur as the first line printed, not the last? Why do the 'done future print's occur after the 'done' print?
How do I get myCall
to only return when the array iteration is complete?
Upvotes: 1
Views: 65
Reputation: 657158
["0","1","2"].forEach(<callback>)
doesn't wait for futures returned by <callback>
.
If you do
Future myCall( ) async {
for(item in ["0","1","2"]){
print( "about to callback");
await futurePrint( item);
print( "done callback");
});
print( "done mycall");
return new Future.value();
}
it should do what you expect.
Upvotes: 1