4
votes

Based on Dart official page When using Async/Wait:

When the app sees the word async it execute the function normally synchronously, until it sees await or return

Note that an async function starts executing right away (synchronously). The function suspends execution and returns an uncompleted future when it reaches the first occurrence of any of the following:

  • The function’s first await expression (after the function gets the uncompleted future from that expression).
  • Any return statement in the function.
  • The end of the function body.

and when it sees any of them it returns an uncompleted Future and stops executing the async function until it execute all of the other functions, and when all of the other functions are executed, the app goes back to the async function and executes what's inside of it.

Here's a photo from the Dart official page explaining it in more details:
Dart Image

But when I was testing that I tried to add a print statement before returning the future result as you can see in the below code, but the result wasn't as stated in the site, as it's saying that the app stops executing once it sees the word awaitbut the statement: "Async - Hi Called 1st" was printed as you can see before the other functions were executed.

import 'dart:async';

Future<void> print1stAsync() async {
  var test = await callAsync();
  print(test);
}

main() {
  print1stAsync();
  print2nd();
  print3rd();
  print4th();
}

print2nd() {
  print('Called 2nd');
}

print3rd() {
  print("Called 3rd");
}

print4th() {
  print('Called 4th');
}

Future<String> callAsync() {
  print("Async - Hi Called 1st");
    return Future(() => "Async - Called 1st ");
  }

Output:

Async - Hi Called 1st
Called 2nd
Called 3rd
Called 4th
Async - Called 1st 

So why is this happening? have I miss understood something?

1

1 Answers

3
votes

The app doesn't stop executing, only the execution of the code after await is delayed until the returned Future completes.

You also need to await the call to the async function print1stAsync(), otherwise the execution of main continues after the call to callAsync(); (after the call, not after the Future it returns completes)

main() async {
  await print1stAsync();
  print2nd();
  print3rd();
  print4th();
}

Add async to a function also means that this function returns a Future. There is no way to go back from async to sync. Async is contagious.

await callAsync(); means code below that line within the same function (like print(test); in your example) will be delayed.
It doesn't say anything about code in callAsync() or code that calls print1stAsync();