我想了解Dart如何执行异步调用。
给出以下代码:
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();
}
我希望输出为
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
但代码实际输出是
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
为什么'完成myCall'发生在第一行打印,而不是最后一行? 为什么未来的印刷品会在完成'之后发生。打印?
如何让myCall
仅在数组迭代完成时返回?
答案 0 :(得分:1)
["0","1","2"].forEach(<callback>)
不等待<callback>
返回的期货。
如果你这样做
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();
}
它应该做你期望的。