Home > Enterprise >  Dart async execution order
Dart async execution order

Time:10-26

I'm trying to understand proper execution order of async functions in Dart. Here is a code that puzzles me:

void main() async {
  print(1);
  f1();
  print(3);
}

void f1() async {
  print(2);
}

According to spec first main() will be executed then f1(). So I expect output:

1
3
2

However real output is:

1
2
3

Does it mean f1() is executed synchronously?

However if I add await Future.delayed(Duration.zero); to f1() before print the output is as I expect:

void main() async {
  print(1);
  f1();
  print(3);
}

void f1() async {
  await Future.delayed(Duration.zero);
  print(2);
}
1
3
2

Can anyone explain that?

CodePudding user response:

Just adding the word async does not make a function asynchronous. If you mark a function that is fully synchronous async, it will execute as any other synchronous function/code would. When you add the Future.delayed, it makes the function actually asynchronous, which puts your print(2) in the event queue so that it's executed later than print(3).

CodePudding user response:

Referring to previous answer there are two quotes from documentation that explain this:

asynchronous function: An asynchronous function performs at least one asynchronous operation and can also perform synchronous operations.

An async function runs synchronously until the first await keyword.

  • Related