Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an async method needs to return a future?

Tags:

dart

I am trying to wrap my head around this. I have to be understanding incorrectly.

Example:

Future A() { ..}

Future B() async{
   await A();
   print "123";
}

Why does B need to return a Future? Doesn't await make B() synchronous? i.e., It waits for A to completely finish and then executes the print statement.

Then, What is the necessity for B to return a Future?

like image 597
Eternalcode Avatar asked Feb 13 '16 04:02

Eternalcode


People also ask

Why must async methods return task?

For methods other than event handlers that don't return a value, you should return a Task instead, because an async method that returns void can't be awaited. Any caller of such a method must continue to completion without waiting for the called async method to finish.

Why async should not return void?

Async void methods can wreak havoc if the caller isn't expecting them to be async. When the return type is Task, the caller knows it's dealing with a future operation; when the return type is void, the caller might assume the method is complete by the time it returns.

Do async functions need to be awaited?

Async/await does not do that. Nothing in Javascript does that. You always get a returned promise from an async function and no use of await inside that function changes that.

Do async functions return immediately?

With that design, you call the asynchronous function, passing in your callback function. The function returns immediately and calls your callback when the operation is finished. With a promise-based API, the asynchronous function starts the operation and returns a Promise object.


1 Answers

async and await don't make async execution sync. There is no way to do that.

All async and await does is to make async code look more like sync code. It is just syntactic sugar. Everything that can be done with async and await can be done without it as well.

Instead of deeply nested .then(...then(...then(...).catchError())).catchError(...) distinct statements, for loops, try, catch, finally can be used which makes code easier to write, read and reason about.

like image 162
Günter Zöchbauer Avatar answered Sep 29 '22 21:09

Günter Zöchbauer