5
votes

Consider this (textbook) sample dart code:

// Sequential processing using async and await.
main() async {
  await expensiveA();
  await expensiveB();
  doSomethingWith(await expensiveC());
}

I understand that await will wait for the result of the future "expensiveA" to complete before continuing.

But what I don't understand is why main() must itself be declared async? Apparently you have to do this or the program will not compile. But why can a synchronous method not await the result of asynchronous calls?

I understand this must be a newbie question but I have not been able to find an answer for this yet.

2

2 Answers

5
votes

Before async/await, which was only added a while ago to Dart, you would have written like

main() {
  var result = expensiveA()
    .then((_) => expensiveB())
    .then((_) => expensiveC()); // the Future returned by expensiveC will be returned because `doSomethingWith` is not awaited in your code
  result.then(doSomethingWith);
  return result;
}

An async call returns a Future, and you can pass a function to it's then method to be called when the async call completes.

This code

main() async {
  await expensiveA();
  await expensiveB();
  doSomethingWith(await expensiveC()); // doSomethingWith is not awaited
}

get's rewritten to something similar to the code in the first code block, before it's executed.

This shows that async/await doesn't change the nature of the code, it only changes the syntax to something that looks more like sync code.

async is a marker that the code in the method needs to be rewritten, and this marker allows the use of await, without rewriting await would have no meaning.

async implicitly returns the last awaited Future, so that the caller is able to await the completion of this Future. Because a Future is returned, strong mode requires the return type to match.

2
votes

Why can a synchronous method not await the result of asynchronous calls? Because that would mean blocking until expensive call is finished.

However Dart is single threaded with event loop, so having easy way to block whole Dart app would be extremely dangerous.