Async/await explained: what actually happens under the hood?
Async/await makes asynchronous code look almost like regular sequential code. That convenience hides some interesting machinery.
The problem it solves: Many operations, like network requests, database queries and file reads, spend most of their time waiting. Blocking a thread while waiting wastes resources. Callbacks avoid blocking but become hard to read when nested.
What async and await do:
- An
asyncfunction returns a promise/future/task: an object representing a value that will be available later. awaitpauses that function until the result is ready, without blocking the whole thread.- While it is paused, the event loop or runtime scheduler runs other work.
- When the result arrives, the function resumes where it left off.
Under the hood:
Compilers typically transform async functions into state machines. Each await is a point where the function can be suspended, its local variables saved, and later restored.
Common pitfalls:
- Sequential awaits when tasks could run concurrently. Starting several requests and awaiting them together (for example with
Promise.allorasyncio.gather) is often much faster. - Blocking calls inside async code, like CPU-heavy loops or synchronous I/O, which freeze the event loop.
- Forgetting to await, leaving errors unhandled.
- Assuming parallelism: async gives concurrency, not necessarily multiple cores.
Which language's async model do you find cleanest? What async bug took you longest to track down?
Comments · 3
The explanation that clicked for me: await just pauses that function and lets everything else keep running. The function picks up again when the result is ready.
Right, and the engine's event loop handles the rest. A promise is basically a ticket the function holds until the result is ready.
Remember it's still one thread in JS. Await doesn't make heavy computing faster, it only keeps waiting from blocking the rest.