DEV Community

Cover image for πŸ”‡ Almost Muted Truth about the JavaScript async/await Mechanism
Emrah URHAN
Emrah URHAN

Posted on

πŸ”‡ Almost Muted Truth about the JavaScript async/await Mechanism

It is commonly said that JavaScript environments like Node.js and others are single threaded. Yes, they are, but it is when you look from the PoV of the JavaScript developer, it is not when you look at the things under the hood.

Developers think that when you await an async call or promise, the whole execution world stops, and the event loop cycles are stopped or queue will overflow if we use too many awaits in our code. But they are missing the tip, "Every await must be in an async function". So, every await is in an async call and event loop cycles when we are waiting an await. But, using awaits excessively may cause larger call stacks and in someway it might damage our executions, but this has a completely another story.

To sum up, async/awaits are about execution order in a single context. Single threaded features of JavaScript runtimes are about adding a call into the event loop, it is not about how they are executed in the background or OS level threads.

A paragraph from MDN expresses this in the paragraph;
"Because await is only valid inside async functions and modules, which themselves are asynchronous and return promises, the await expression never blocks the main thread and only defers execution of code that actually depends on the result, i.e. anything after the await expression.".

MDN await

πŸ“· Ferenc Almasi on Unsplash

Top comments (0)