In general, all functions that contain await
must be async
.
That rule might make more sense if we imagine it would not exist, and if you could wait for an asynchronous result in a synchronous function.
First of all, we need to know one important things about functions:
They have to run to completion, or in other words: A regular function runs till it's return
and no other code can run at the same time.
If we could await
inside of a non-async function that would mean that we would block execution until the awaited promise resolves, as no other code can run in the meantime. As the code that resolves the promise also cannot run, we created a deadlock.
async function
s only run to completion till they reach an await
. Therefore, when axios.get(...)
gets called, a promise gets returned synchronously from it, funcTwo
halts execution, returns a promise itself, therefore funcOne
also halts execution (thats possible cause it's async
). Then the engine can continue with other stuff, and somewhen when the underlying request is done, the promise resolves, funcTwo
continues execution which resolves the promise it returned, funcOne
continues execution and resolves the returned promise too.
If my second function is async isn't that non-blocking?
That really depends on your definition of non-blocking. In general, every code of JS that executes kind of "blocks the thread" (as only one function can execute at a time), but as most tasks are very small, you won't notice that blocking.
An asnyc function
is also blocking, as long as it doesn't halt for a promise to resolve. Then it is in a non-blocking waiting state.
Asynchronous tasks (e.g. doing a network request) also aren't blocking, cause they are handled by the engine (offloaded to other threads or hardware, etc.).