{
    "slug": "async_await",
    "term": "async / await in JavaScript",
    "category": "javascript",
    "difficulty": "intermediate",
    "short": "async functions always return a Promise; await pauses execution inside an async function until a Promise settles — giving asynchronous code the readability of synchronous code without blocking the event loop.",
    "long": "async/await is syntactic sugar over Promises, introduced in ES2017. Marking a function async makes it return a Promise implicitly — even a bare return value is wrapped. Inside an async function, await suspends execution until the awaited Promise resolves, then resumes with the resolved value. If the Promise rejects, await throws the rejection reason, making try/catch the natural error-handling pattern. Crucially, await does not block the thread — while waiting, the event loop is free to run other tasks. Multiple independent async operations should be parallelised with Promise.all() rather than awaited sequentially. Top-level await is supported in ES modules. Common pitfalls: forgetting await (getting a Promise instead of its value), sequential awaiting in a loop instead of parallelising, and unhandled rejections when an async function throws inside an event handler with no wrapping try/catch.",
    "aliases": [
        "async functions",
        "await keyword",
        "ES2017 async",
        "async/await pattern"
    ],
    "tags": [
        "javascript",
        "async",
        "promises",
        "concurrency",
        "es2017",
        "event-loop"
    ],
    "misconception": "await does not block the thread or pause the event loop — it only suspends the current async function, allowing other callbacks and tasks to run while waiting.",
    "why_it_matters": "async/await eliminates callback hell and Promise chain nesting, making asynchronous code readable and maintainable — most modern JS codebases including Node.js backends and browser fetch calls rely on it.",
    "common_mistakes": [
        "Forgetting await — const data = fetch(url) gives a Promise object, not the response body.",
        "Awaiting in a loop sequentially when the iterations are independent — use Promise.all() to run them in parallel.",
        "Missing try/catch around await — an unhandled rejection inside an async function crashes Node.js workers or produces silent failures in browsers.",
        "Using async in an Array.forEach callback — forEach does not await the returned Promises, so the loop finishes before the async work completes."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "js_promises",
        "js_event_loop",
        "js_fetch_api",
        "js_generators",
        "py_error_handling"
    ],
    "prerequisites": [
        "js_promises",
        "js_event_loop"
    ],
    "refs": [
        "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function",
        "https://v8.dev/blog/fast-async"
    ],
    "bad_code": "// Sequential awaits — total time = sum of all request times:\nasync function loadAll(ids) {\n    const results = [];\n    for (const id of ids) {\n        results.push(await fetch(`/api/${id}`)); // waits for each in turn\n    }\n    return results;\n}",
    "good_code": "// Parallel with Promise.all — total time = slowest single request:\nasync function loadAll(ids) {\n    const promises = ids.map(id => fetch(`/api/${id}`));\n    return Promise.all(promises); // all requests in flight simultaneously\n}",
    "example_note": "The bad example awaits each fetch in sequence — 10 requests × 200ms = 2 seconds total. Promise.all fires all requests simultaneously, completing in ~200ms regardless of count.",
    "quick_fix": "Replace sequential await-in-loop with Promise.all(items.map(item => asyncFn(item)))",
    "severity": "low",
    "effort": "low",
    "created": "2026-04-10",
    "updated": "2026-04-10",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/async_await",
        "html_url": "https://codeclaritylab.com/glossary/async_await",
        "json_url": "https://codeclaritylab.com/glossary/async_await.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[async / await in JavaScript](https://codeclaritylab.com/glossary/async_await) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/async_await"
            }
        }
    }
}