Why in the following program Asynchronous function is being Called before Synchronous?

Issue

showAsync() {
  print('Async Function Call!!');    
}

show() async {
  await showAsync();
  print('all done!!');
}

showSync() {
  print('Sync Function Call!');
}

main(List<String> args) {
  show();
  showSync();
}

Output:

Async Function Call!!
Sync Function Call!
all done!!

Solution

The showAsync function is not doing anything that requires waiting, so it just executes. If you change to the following, the other functions will print first:

showAsync() {
  Future.delayed(Duration(seconds: 1), () {
    print('Async Function Call!!');
  });
}

As G√ľnter pointed out in the comments: “In Dart 1.x, async functions immediately suspended execution. In Dart 2, instead of immediately suspending, async functions execute synchronously until the first await or return.” (quote from the Dart docs).

So, if you add a second await showAsync(), it will not execute before the sync call.

A detailed explanation is available here: https://www.dartlang.org/tutorials/language/futures

Answered By – Vinicius Pinto

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.