Reputation: 476
I now understand that async functions return promises of values not values directly. But what I don't understand is what the point of doing that in the first place. As far as I understand, async functions are used to synchronize code inside them, now after we got the value from a promise using the await statement inside the async function, why should we return another promise? Why don't we just return the result directly or return void?
Upvotes: 0
Views: 59
Reputation: 664307
Yes, async function
are used to sequentialise the code inside them. They do not - cannot - stop the code execution outside of them. As you probably remember, blocking is bad. You cannot get the result from the future of course, but you don't want to stop the world just to wait for that function to finish either. And that's why when you call such a function, you get back a promise that you either await
, or can schedule a callback on and do other things while it waits.
Upvotes: 1
Reputation: 222369
async functions are used to synchronize code inside them
They aren't. async
functions provide syntactic sugar for promises, thus eliminating the need to use callbacks. async
function acts exactly like regular function that returns a promise.
There's no way how the result can be returned synchronously from asynchronous function.
If the result should be returned from async
function, it should be called and await
ed inside another async
function, and so on - possibly up to application entry point.
Upvotes: 2
Reputation: 68635
Because you can't know when the asynchronous call will be done. So it just returns a promise to let you make your rest logic with asynchronous call by making then
-s chain.
Upvotes: 1