--- id: javascript-async-callbacks title: "JavaScript Async Callbacks" category: "Frontend" status: "draft" verification_status: "conceptual" canonical_id: "" aliases: ["Callbacks", "Callback functions", "Error-first callbacks", "Callback hell", "JS callbacks"] duplicate_of: "" source_trust_level: "B" confidence_score: 0.88 created_at: 2026-06-23 updated_at: 2026-06-23 review_reason: "" merge_history: [] tags: ["javascript", "js", "web", "frontend", "w3schools", "callbacks", "asynchronous"] raw_sources: ["https://www.w3schools.com/js/js_async_callbacks.asp"] applied_in: [] github_commit: "" --- # [[JavaScript Async Callbacks]] ## 🎯 ν•œ 쀄 톡찰 (One-line insight) A callback is a function passed as an argument into another function, intended to run later β€” the first solution for sequencing asynchronous JavaScript. [S1] ## 🧠 핡심 κ°œλ… (Core concepts) - **What a callback is** β€” a function passed as an argument into another function, intended for later execution, typically when an event occurs or an async operation completes. [S1] - **Why callbacks exist** β€” async code finishes later, so you cannot return its result immediately; instead you pass a callback to run once the result is ready, enabling sequential control. [S1] - **Error-first pattern** β€” pass two parameters, error first then data, so the function can handle failures gracefully. [S1] - **Callback hell** β€” deeply nested callbacks create complex, hard-to-read structures that complicate debugging. [S1] - **Modern alternatives** β€” Promises and async/await provide cleaner flow and better error handling, and modern asynchronous JavaScript does not use callbacks. [S1] ## 🧩 μΆ”μΆœλœ νŒ¨ν„΄ (Extracted patterns) - **Pass-a-function-to-run-later** β€” give a function a callback parameter and invoke it once work is done (e.g. `myCalculator(5, 5, myDisplayer)`). [S1] - **Error-first signature** β€” `callback(error, data)`; check `error` first and `return` early on failure. [S1] - **Event-listener callback** β€” `addEventListener("click", displayDate)` runs the callback on the event. [S1] ## πŸ“– μ„ΈλΆ€ λ‚΄μš© (Details) **Event handling** Callbacks handle user interactions through event listeners; the listener runs the callback when the user clicks: [S1] ```javascript document.getElementById("myButton").addEventListener("click", displayDate); ``` **Asynchronous operations with setTimeout** `setTimeout()` uses a callback that executes after the delay without freezing the page: [S1] ```javascript setTimeout(myFunction, 3000); function myFunction() { document.getElementById("demo").innerHTML = "I love You !!"; } ``` **The timing problem** Async code finishes later, so the result is not available immediately: [S1] ```javascript let result; setTimeout(function() { result = 5; }, 1000); // What is result here? ``` **The callback idea** Instead of reading the result directly, pass it into a function that runs when ready: [S1] ```javascript function done(value) { myDisplayer(value); } setTimeout(function() { done(5); }, 1000); // What is result here? ``` **Sequence control β€” first approach (return then display)** [S1] ```javascript function myDisplayer(some) { document.getElementById("demo").innerHTML = some; } function myCalculator(num1, num2) { let sum = num1 + num2; return sum; } let result = myCalculator(5, 5); myDisplayer(result); ``` **Sequence control β€” second approach (display inside)** [S1] ```javascript function myDisplayer(some) { document.getElementById("demo").innerHTML = some; } function myCalculator(num1, num2) { let sum = num1 + num2; myDisplayer(sum); } myCalculator(5, 5); ``` **Using callbacks** Pass the displayer in as a callback so the caller controls what happens with the result: [S1] ```javascript function myDisplayer(some) { document.getElementById("demo").innerHTML = some; } function myCalculator(num1, num2, myCallback) { let sum = num1 + num2; myCallback(sum); } myCalculator(5, 5, myDisplayer); ``` **Error-first callbacks β€” success case** [S1] ```javascript function getData(callback) { let ok = true; if (ok) { callback(null, "Data"); } else { callback("Something failed", null); } } getData(function(error, data) { if (error) { myDisplayer(error); return; } myDisplayer(data); }); ``` **Error-first callbacks β€” failure case** [S1] ```javascript function getData(callback) { let ok = false; if (ok) { callback(null, "Data"); } else { callback("Something failed", null); } } getData(function(error, data) { if (error) { myDisplayer(error); return; } myDisplayer(data); }); ``` **Callback drawbacks (callback hell)** Deeply nested callbacks become hard to read and debug: [S1] ```javascript step1(function(r1) { step2(r1, function(r2) { step3(r2, function(r3) { console.log(r3); }); }); }); ``` Modern asynchronous JavaScript does not use callbacks; Promises and async/await are recommended instead. [S1] ## πŸ› οΈ 적용 사둀 (Applied in summary) The page's snippets β€” the `myCalculator(5, 5, myDisplayer)` callback handoff, the error-first `getData` pattern, and the nested `step1/step2/step3` "callback hell" β€” are the canonical applied examples. No external project/commit applications found in the source. ## πŸ’» μ½”λ“œ νŒ¨ν„΄ (Code patterns) Pass a callback to run later (language: JavaScript): ```javascript function myCalculator(num1, num2, myCallback) { let sum = num1 + num2; myCallback(sum); } myCalculator(5, 5, myDisplayer); ``` Error-first callback: ```javascript getData(function(error, data) { if (error) { myDisplayer(error); return; } myDisplayer(data); }); ``` ## βš–οΈ 비ꡐ 및 선택 κΈ°μ€€ (Comparison & decision criteria) - **Callbacks** β€” the original async solution; pass a function to run later. Drawback: nesting becomes "callback hell," hard to read and chain. [S1] - **Promises / async-await** β€” recommended modern alternatives providing cleaner flow and better error handling; modern asynchronous JavaScript does not use callbacks. [S1] ## βš–οΈ λͺ¨μˆœ 및 μ—…λ°μ΄νŠΈ (Contradictions & updates) No contradictions found in the source. ## βœ… 검증 μƒνƒœ 및 신뒰도 - **μƒνƒœ:** draft - **검증 단계:** conceptual (μ‹€μ œ 적용 사둀 발견 μ‹œ applied/validated둜 승격 κ°€λŠ₯) - **좜처 신뒰도:** B (W3Schools β€” widely used educational reference, not a primary standards body) - **μ‹ λ’° 점수:** 0.88 - **쀑볡 검사 κ²°κ³Ό:** μ‹ κ·œ 생성 (New discovery) ## πŸ”— 지식 κ·Έλž˜ν”„ (Knowledge Graph) - **μƒμœ„/루트:** [[JavaScript Tutorial]] - **κ΄€λ ¨ κ°œλ…:** [[JavaScript Async Timeouts]], [[JavaScript Promise]], [[JavaScript Async Await]], [[JavaScript Async]] - **μ°Έμ‘° λ§₯락:** The first solution to async sequencing, motivating Promises as the cleaner successor. ## πŸ“š 좜처 (Sources) - [S1] W3Schools β€” JavaScript Async Callbacks β€” https://www.w3schools.com/js/js_async_callbacks.asp ## πŸ“ λ³€κ²½ 이λ ₯ (Change history) - 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Async Callbacks" page (Astra wiki-curation, P-Reinforce v3.1 format).