Why Can’t I Use Async/Await in Synchronous Functions?

0
4
Asked By CuriousCoder42 On

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?

1 Answer

Answered By TechWhiz88 On

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.

RustyRaptor -

Gotcha! I think I get it now. It’s all about how the runtime manages state and functions, right? Thanks for clarifying that!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.