Why for methods that call async methods?

Consider this sample code (tutorial):

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

I understand that I will wait and wait until the future "darling" is completed before continuing.

But I don’t understand why main () must itself be declared async? Apparently you need to do this or the program will not compile. But why doesn't the synchronous method wait for the result of asynchronous calls?

I understand that this should be a question for beginners, but so far I have not been able to find the answer.

+4
source share
2 answers

Before async/ await, which was recently added by Dart, you would write as

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;
}

Future, then, , async .

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

- , .

, async/await , , .

async , , await, await .

async await ed Future, await Future. Future, , .

+4

? , .

Dart , Dart .

+2

Source: https://habr.com/ru/post/1684804/


All Articles