Async/Await
Async/await is a syntactic sugar for working with asynchronous operations (Promises) in a way that looks and behaves like synchronous code.
Core Principles: 1. Async: Declares an asynchronous function. 2. Await: Pauses execution until a promise is settled. 3. Error Handling: Uses standard try...catch blocks. 4. Return Value: Always a Promise. 5. Non-Blocking: The main execution thread continues other tasks while waiting.
graph LR
Center["Async/Await"]:::main
Pre_algorithms["algorithms"]:::pre --> Center
click Pre_algorithms "/terms/algorithms"
Rel_big_o_notation["big-o-notation"]:::related -.-> Center
click Rel_big_o_notation "/terms/big-o-notation"
Rel_algorithms["algorithms"]:::related -.-> Center
click Rel_algorithms "/terms/algorithms"
Rel_space_complexity["space-complexity"]:::related -.-> Center
click Rel_space_complexity "/terms/space-complexity"
classDef main fill:#7c3aed,stroke:#8b5cf6,stroke-width:2px,color:white,font-weight:bold,rx:5,ry:5;
classDef pre fill:#0f172a,stroke:#3b82f6,color:#94a3b8,rx:5,ry:5;
classDef child fill:#0f172a,stroke:#10b981,color:#94a3b8,rx:5,ry:5;
classDef related fill:#0f172a,stroke:#8b5cf6,stroke-dasharray: 5 5,color:#94a3b8,rx:5,ry:5;
linkStyle default stroke:#4b5563,stroke-width:2px;
🧒 5 yaşındaki gibi açıkla
Imagine you're at a coffee shop. You order a latte. In a 'synchronous' shop, you'd stand at the counter waiting and blocking everyone else until your latte is ready. In an 'async/await' shop, you order, sit down with a vibrating pager (the Promise), and then you only 'wait' (await) when the pager goes off, but the shop keeps serving other people in the meantime.
🤓 Expert Deep Dive
When the await keyword is encountered, the execution context of the async function is suspended and control is returned to the event [loop](/tr/terms/event-loop). The state of the function (variables, stack) is saved. Once the awaited Promise fulfills, the function is added back to the 'Microtask' queue and resumed. Key performance optimizations include the avoidance of 'Zalgo' (ensuring consistent asynchronous behavior) and the reduction of cognitive load when nesting multiple dependent asynchronous calls. However, improper use of await in loops can lead to 'Sequential Execution' when parallel execution (via Promise.all) would be more efficient.