DEV Community

Discussion on: Help me make some JS functions asynchronous

Collapse
bacloud14 profile image
bacloud14 Author

I have a question on the "async" method, I thought it is blocking, which defeats the purpose or am I wrong, won't it block the main thread in NodeJS ?

Collapse
sargalias profile image
Spyros Argalias

You're welcome. I'm glad it's helpful :).

Async / await only blocks the code in the specific function. While it's "awaiting", it frees up the main thread so it can do other work. When the code it's waiting on completes (for example, when db.toPublic() has completed its asynchronous operation), and when the main thread is free again, execution inside that function resumes. If it hits another "await" statement, the process repeats (it frees up the main thread and waits for the asynchronous operation to complete).

It actually uses promises behind the scenes, so it has the same effect. In the examples above with the .then and async, they both do the same thing and handle the main thread the same way.

Thread Thread
bacloud14 profile image
bacloud14 Author

thanks again for explanations 💚,