This is the code that uses Future
void main(List<String> arguments) {
testFuture();
print('main');
}
Future testFuture() {
return Future(() {
for (var i = 0; i < 1000000000; i++) {}
print('futureDone');
});
}
The output is as follows
main
futureDone
When I want to use async to simplify my code, the code looks like this
Future testFuture() async{
for (var i = 0; i < 1000000000; i++) {}
print('futureDone');
}
The output is as follows
futureDone
main
At first I was confused, I don't know why they output is different, I am looking for a lot of information, until I saw these words on the https://dart.dev/codelabs/async-await#execution-flow-with-async-and-await。
An async function runs synchronously until the first await keyword. This means that within an async function body, all synchronous code before the first await keyword executes immediately.
I don't know why,So with that in mind, if I want to use async I need to write code like this.
Future testFuture() async{
await Future.delayed(Duration(seconds: 0));
for (var i = 0; i < 1000000000; i++) {}
print('futureDone');
}
The output is as follows
main
futureDone
By reading the StackFlow problem in older versions of Dart, I found that the old version didn't "An async function runs synchronously until the first await the keyword. This means that within An async function body, All synchronous code before the first await keyword Executes immediately. ", why did DART make such a change? Or is there something wrong with the way I use it?
async
method is most likely to be calling some code where we want to wait for the result. And maybe, there are a possibility that we don't always ends upawait
on something (e.g. if we implement some kind of cache). – julemand101