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>
301 lines
8.2 KiB
Markdown
301 lines
8.2 KiB
Markdown
---
|
|
id: javascript-promises
|
|
title: "JavaScript Promises"
|
|
category: "Frontend"
|
|
status: "draft"
|
|
verification_status: "conceptual"
|
|
canonical_id: ""
|
|
aliases: ["Promise", "Promises", "Promise.resolve", "Promise.reject", "Promise chaining", "then catch"]
|
|
duplicate_of: ""
|
|
source_trust_level: "B"
|
|
confidence_score: 0.89
|
|
created_at: 2026-06-23
|
|
updated_at: 2026-06-23
|
|
review_reason: ""
|
|
merge_history: []
|
|
tags: ["javascript", "js", "web", "frontend", "w3schools", "promises", "asynchronous"]
|
|
raw_sources: ["https://www.w3schools.com/js/js_promise.asp"]
|
|
applied_in: []
|
|
github_commit: ""
|
|
---
|
|
|
|
# [[JavaScript Promises]]
|
|
|
|
## 🎯 한 줄 통찰 (One-line insight)
|
|
A Promise is an object representing the eventual completion or failure of an asynchronous operation, letting you chain steps with `then()`/`catch()` instead of nesting callbacks. [S1]
|
|
|
|
## 🧠 핵심 개념 (Core concepts)
|
|
- **Promises replace callback nesting** — they were created to make asynchronous JavaScript easier than deeply nested callbacks ("callback hell"). [S1]
|
|
- **Three states** — a Promise is pending, fulfilled (resolved), or rejected. [S1]
|
|
- **Construct with resolve/reject** — `new Promise(function(resolve, reject) { ... })`; call `resolve(value)` on success or `reject(value)` on failure. [S1]
|
|
- **Consume with then/catch** — `then()` takes success (and optional failure) handlers; `catch()` handles rejection across a chain. [S1]
|
|
- **Chaining requires return** — each `then()` should `return` the next promise so the chain links correctly; forgetting to return breaks the chain. [S1]
|
|
- **Shortcuts** — `Promise.resolve(value)` and `Promise.reject(value)` create already-settled promises. [S1]
|
|
|
|
## 🧩 추출된 패턴 (Extracted patterns)
|
|
- **Resolve/reject wrapper** — wrap slow work in `new Promise`, calling `resolve`/`reject` when done. [S1]
|
|
- **then-chain with return** — `step1().then(v => step2(v)).then(v => step3(v))...` runs steps in sequence. [S1]
|
|
- **Single catch for the chain** — one `.catch()` at the end handles any failure along the chain. [S1]
|
|
- **Promisify a timer or XHR** — wrap `setTimeout` or `XMLHttpRequest` so its completion resolves a promise. [S1]
|
|
|
|
## 📖 세부 내용 (Details)
|
|
**The problem promises solve (callback hell)**
|
|
Deeply nested callbacks are hard to read: [S1]
|
|
```javascript
|
|
step1(function(r1) {
|
|
step2(r1, function(r2) {
|
|
step3(r2, function(r3) {
|
|
console.log(r3);
|
|
});
|
|
});
|
|
});
|
|
```
|
|
|
|
**Promise syntax — resolve case**
|
|
[S1]
|
|
```javascript
|
|
let myPromise = new Promise(function(resolve, reject) {
|
|
ok = true;
|
|
|
|
// Code that may take some time
|
|
|
|
if (ok) {
|
|
resolve("OK");
|
|
} else {
|
|
reject("Error");
|
|
}
|
|
});
|
|
|
|
// Using then() to display the result
|
|
myPromise.then(
|
|
function(value) {myDisplayer(value);},
|
|
function(value) {myDisplayer(value);}
|
|
);
|
|
```
|
|
|
|
**Promise syntax — reject case**
|
|
[S1]
|
|
```javascript
|
|
let myPromise = new Promise(function(resolve, reject) {
|
|
ok = false;
|
|
|
|
// Code that may take some time
|
|
|
|
if (ok) {
|
|
resolve("OK");
|
|
} else {
|
|
reject("Error");
|
|
}
|
|
});
|
|
|
|
// Using then() to display the result
|
|
myPromise.then(
|
|
function(value) {myDisplayer(value);},
|
|
function(value) {myDisplayer(value);}
|
|
);
|
|
```
|
|
|
|
**Promise.resolve()**
|
|
[S1]
|
|
```javascript
|
|
let promise = Promise.resolve("OK");
|
|
|
|
promise
|
|
.then(function(value) {
|
|
console.log(value);
|
|
})
|
|
.catch(function(value) {
|
|
myDisplayer(value);
|
|
});
|
|
```
|
|
|
|
**Promise.reject()**
|
|
[S1]
|
|
```javascript
|
|
let promise = Promise.reject("Error");
|
|
|
|
promise
|
|
.then(function(value) {
|
|
console.log(value);
|
|
})
|
|
.catch(function(value) {
|
|
myDisplayer(value);
|
|
});
|
|
```
|
|
|
|
**Promise chaining**
|
|
Run three functions in steps, each returning a promise: [S1]
|
|
```javascript
|
|
// Three functions to run in steps
|
|
function step1() {
|
|
return Promise.resolve("A");
|
|
}
|
|
function step2(value) {
|
|
return Promise.resolve(value + "B");
|
|
}
|
|
function step3(value) {
|
|
return Promise.resolve(value + "C");
|
|
}
|
|
|
|
// Run the three functions in steps
|
|
step1()
|
|
.then(function(value) {
|
|
return step2(value);
|
|
})
|
|
.then(function(value) {
|
|
return step3(value);
|
|
})
|
|
.then(function(value) {
|
|
myDisplayer(value);
|
|
});
|
|
```
|
|
|
|
**Error handling with catch()**
|
|
A single `catch()` handles failure anywhere in the chain: [S1]
|
|
```javascript
|
|
step1()
|
|
.then(function(value) {
|
|
return step2(value);
|
|
})
|
|
.then(function(value) {
|
|
return step3(value);
|
|
})
|
|
.catch(function(error) {
|
|
console.log(error);
|
|
});
|
|
```
|
|
|
|
**Common mistake — forgetting to return**
|
|
Without `return`, the next `then()` does not receive the resolved value: [S1]
|
|
```javascript
|
|
step1()
|
|
.then(function(value) {
|
|
step2(value);
|
|
})
|
|
.then(function(value) {
|
|
console.log(value);
|
|
});
|
|
```
|
|
|
|
**Fetch API with promises**
|
|
[S1]
|
|
```javascript
|
|
fetch("data.json")
|
|
.then(function(response) {
|
|
return response.json();
|
|
})
|
|
.then(function(data) {
|
|
console.log(data);
|
|
})
|
|
.catch(function(error) {
|
|
console.log(error);
|
|
});
|
|
```
|
|
|
|
**Timeout with a callback vs a promise**
|
|
Callback version: [S1]
|
|
```javascript
|
|
setTimeout(function() { myFunction("I love You !!!"); }, 3000);
|
|
|
|
function myFunction(value) {
|
|
document.getElementById("demo").innerHTML = value;
|
|
}
|
|
```
|
|
Promise version (promisified timer): [S1]
|
|
```javascript
|
|
let myPromise = new Promise(function(myResolve, myReject) {
|
|
setTimeout(function() { myResolve("I love You !!"); }, 3000);
|
|
});
|
|
|
|
myPromise.then(function(value) {
|
|
document.getElementById("demo").innerHTML = value;
|
|
});
|
|
```
|
|
|
|
**File loading — callback vs promise**
|
|
Callback version using XMLHttpRequest: [S1]
|
|
```javascript
|
|
function getFile(myCallback) {
|
|
let req = new XMLHttpRequest();
|
|
req.open('GET', "mycar.html");
|
|
req.onload = function() {
|
|
if (req.status == 200) {
|
|
myCallback(req.responseText);
|
|
} else {
|
|
myCallback("Error: " + req.status);
|
|
}
|
|
}
|
|
req.send();
|
|
}
|
|
|
|
getFile(myDisplayer);
|
|
```
|
|
Promise version: [S1]
|
|
```javascript
|
|
let myPromise = new Promise(function(myResolve, myReject) {
|
|
let req = new XMLHttpRequest();
|
|
req.open('GET', "mycar.html");
|
|
req.onload = function() {
|
|
if (req.status == 200) {
|
|
myResolve(req.response);
|
|
} else {
|
|
myReject("File not Found");
|
|
}
|
|
};
|
|
req.send();
|
|
});
|
|
|
|
myPromise.then(
|
|
function(value) {myDisplayer(value);},
|
|
function(error) {myDisplayer(error);}
|
|
);
|
|
```
|
|
|
|
## 🛠️ 적용 사례 (Applied in summary)
|
|
The page's snippets — the `step1/step2/step3` chain, the promisified `setTimeout`, and the promisified `XMLHttpRequest` file loader — are the canonical applied examples. No external project/commit applications found in the source.
|
|
|
|
## 💻 코드 패턴 (Code patterns)
|
|
Construct and consume a promise (language: JavaScript):
|
|
```javascript
|
|
let myPromise = new Promise(function(resolve, reject) {
|
|
if (ok) { resolve("OK"); } else { reject("Error"); }
|
|
});
|
|
|
|
myPromise.then(
|
|
function(value) {myDisplayer(value);},
|
|
function(value) {myDisplayer(value);}
|
|
);
|
|
```
|
|
Chain steps with a single catch:
|
|
```javascript
|
|
step1()
|
|
.then(function(value) { return step2(value); })
|
|
.then(function(value) { return step3(value); })
|
|
.catch(function(error) { console.log(error); });
|
|
```
|
|
|
|
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
|
|
- **Callbacks** — the original approach; deeply nested callbacks become "callback hell," hard to read. [S1]
|
|
- **Promises** — created to make async JavaScript easier; chainable with `then()` and a single `catch()`, but require remembering to `return` each step. [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.89
|
|
- **중복 검사 결과:** 신규 생성 (New discovery)
|
|
|
|
## 🔗 지식 그래프 (Knowledge Graph)
|
|
- **상위/루트:** [[JavaScript Tutorial]]
|
|
- **관련 개념:** [[JavaScript Async Callbacks]], [[JavaScript Async Await]], [[JavaScript Async Fetch]], [[JavaScript Async Timeouts]]
|
|
- **참조 맥락:** The cleaner successor to callbacks and the foundation that async/await is built on.
|
|
|
|
## 📚 출처 (Sources)
|
|
- [S1] W3Schools — JavaScript Promises — https://www.w3schools.com/js/js_promise.asp
|
|
|
|
## 📝 변경 이력 (Change history)
|
|
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Promises" page (Astra wiki-curation, P-Reinforce v3.1 format).
|