Ralfeus
Ralfeus

Reputation: 815

Dart async execution order

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?

Upvotes: 0

Views: 200

Answers (3)

Andrei Iatsuk
Andrei Iatsuk

Reputation: 1

I just want to add more details to Christopher's answer. async function will be executed as synchronous until first await keyword. Then await automatically jumps to the next iteration of the event loop and passes control to the scope of the function we want to wait until it returns a result.

In this case, we are scheduling to print 1, f1 function, to print 3. Printing 1, see await in f1, going to the next iteration, printing 3, awaiting the Future.delayed and then printing 2.

Upvotes: 0

Ralfeus
Ralfeus

Reputation: 815

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.

Upvotes: 1

Christopher Moore
Christopher Moore

Reputation: 17113

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).

Upvotes: 1

Related Questions