Shubhamhackz
Shubhamhackz

Reputation: 7973

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

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!!

Upvotes: 1

Views: 40

Answers (1)

Vinicius Braz Pinto
Vinicius Braz Pinto

Reputation: 8289

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

Upvotes: 2

Related Questions