Why Can't I Use Async/Await in Synchronous Functions?
Asked by
well-read
Hey everyone! I'm diving into asynchronous programming and have been using async/await in my project involving a lot of I/O operations. However, I got confused about why I can't call await in regular synchronous functions. Here's how I thought it worked:
I figured that using 'async' would change the function's return type to something like a promise, stating, "I don't have the answer now, but I will later." Then 'await' should let me wait for the function to finish before moving on, allowing other code to run in the meantime.
So I assumed when calling an async function:
- From a sync function with await, it would wait for the result before continuing.
- From another async function with await, it would get the result while allowing other things to run.
- From any function without await, it would just receive a promise and continue execution without blocking.
But I noticed that I can't use await in a sync function, which means all the parent functions need to be async too, even if I didn't want them to handle other things while waiting.
By the way, I'm using Rust with Tokio for my async operations. Any insights on this?
Answers
It seems like thereโs some misunderstanding about how async/await actually works. In many languages, including JavaScript, async/await is just syntactic sugar for handling promises. It boils down to this:
When you use await in a function, that function must be declared as async because the interpreter needs it to handle the underlying promise resolution properly. So in a synchronous function, it wouldn't know to convert that await call into a promise handling callback.
And you're right about using promises to run other code while waiting, but the key is that you canโt block a synchronous function for an async operation without making it async itself. Thatโs just how the event loop works.
Also, your mention of using multi-threading isn't quite applicable here since async/await is about efficient resource management in single-threaded environments.
Reply to this answer
Add your answer
Answers are reviewed before publication.
_52 seats filled: Gotcha! I think I get it now. Itโs all about how the runtime manages state and functions, right? Thanks for clarifying that!