0

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?

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.