9609c04755
W3Schools 튜토리얼을 P-Reinforce v3.1 포맷으로 위키화(영어 본문, 한/영 섹션 헤더). - Topic_HTML: 59문서 (튜토리얼+예제, 레퍼런스/메타 제외) - Topic_CSS: 190문서 (메인 + Advanced/Flexbox/Grid/RWD 전체) - Topic_JavaScript: 120문서 (코어 언어; Temporal/DOM상세/BOM/WebAPI/AJAX/jQuery/Graphics 등은 후속) 각 폴더 00_INDEX.md(MOC) 포함. 코드 verbatim, 미확인분은 "Not found in source" 표기. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
233 lines
7.0 KiB
Markdown
233 lines
7.0 KiB
Markdown
---
|
|
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).
|