--- 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).