--- id: javascript-async-fetch title: "JavaScript Async Fetch" category: "Frontend" status: "draft" verification_status: "conceptual" canonical_id: "" aliases: ["fetch", "fetch API", "response.json", "response.ok", "HTTP request JavaScript", "XMLHttpRequest vs fetch"] 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", "fetch", "asynchronous", "http"] raw_sources: ["https://www.w3schools.com/js/js_async_fetch.asp"] applied_in: [] github_commit: "" --- # [[JavaScript Async Fetch]] ## 🎯 ν•œ 쀄 톡찰 (One-line insight) `fetch()` is the modern, asynchronous way to request data from a server β€” it returns a promise for a Response, and you must read the body (and check `response.ok`) to get the actual data. [S1] ## 🧠 핡심 κ°œλ… (Core concepts) - **fetch returns a promise** β€” `fetch()` is the modern way to request data from a server; it is asynchronous and returns a promise that becomes a response later. [S1] - **Response is not the data** β€” the result is a `Response` object, not the JSON data; to get JSON you must read the body with `response.json()`, which itself returns a promise. [S1] - **async/await is recommended** β€” `async` and `await` make fetch code easier to read; this is the recommended way for beginners. [S1] - **404/500 do not reject** β€” fetch only rejects on network errors; a 404 response is not a rejected promise, so you must check `response.ok`. [S1] - **Network errors reject** β€” a network error (offline mode, DNS errors) happens when the request cannot be completed and does reject the promise. [S1] - **Forgetting await yields a promise** β€” omitting `await` on `response.json()` logs a promise instead of the data. [S1] ## 🧩 μΆ”μΆœλœ νŒ¨ν„΄ (Extracted patterns) - **fetch β†’ json promise chain** β€” `fetch(url).then(r => r.json()).then(data => ...)`. [S1] - **async/await fetch** β€” `let response = await fetch(url); let data = await response.json();`. [S1] - **Guard with response.ok** β€” check `if (!response.ok)` to handle HTTP errors that fetch will not reject. [S1] - **try/catch for network errors** β€” wrap the await calls to catch true network failures. [S1] ## πŸ“– μ„ΈλΆ€ λ‚΄μš© (Details) **fetch returns a promise, not the data** `fetch()` does not return the data; it returns a promise that becomes a response later. The result is a `Response` object, not the JSON data: [S1] ```javascript fetch("data.json") .then(function(response) { console.log(response); }); ``` **Reading the body** To get JSON you must read the response body; `response.json()` returns a promise. The following is a promise chain: [S1] ```javascript fetch("data.json") .then(function(response) { return response.json(); }) .then(function(data) { console.log(data); }); ``` **async/await version (recommended)** `async` and `await` make fetch code easier to read; this is the recommended way for beginners: [S1] ```javascript async function loadData() { let response = await fetch("data.json"); let data = await response.json(); console.log(data); } loadData(); ``` **Checking response.ok (HTTP errors)** A common beginner mistake is expecting fetch to fail on 404 or 500. Fetch only rejects on network errors; a 404 response is not a rejected promise β€” you must check `response.ok`. The following handles HTTP errors correctly: [S1] ```javascript async function loadData() { let response = await fetch("missing.json"); if (!response.ok) { console.log("HTTP Error:", response.status); return; } let data = await response.json(); console.log(data); } loadData(); ``` **Network errors with try...catch** A network error happens when the request cannot be completed (offline mode, DNS errors); network errors reject the promise: [S1] ```javascript async function loadData() { try { let response = await fetch("data.json"); let data = await response.json(); console.log(data); } catch (error) { console.log("Network error"); } } ``` **Forgetting await on response.json()** Forgetting `await` gives you a promise instead of data; the following logs a promise β€” you must use `await` to get the JSON: [S1] ```javascript async function loadData() { let response = await fetch("data.json"); let data = response.json(); console.log(data); } ``` Correct version: [S1] ```javascript async function loadData() { let response = await fetch("data.json"); let data = await response.json(); console.log(data); } ``` **Callback (XMLHttpRequest) vs fetch** Callback approach with XMLHttpRequest: [S1] ```javascript function loadFile(callback) { let xhr = new XMLHttpRequest(); xhr.open("GET", "data.json", true); xhr.onload = function() { if (xhr.status === 200) { callback(null, JSON.parse(xhr.responseText)); } else { callback("HTTP Error: " + xhr.status, null); } }; xhr.onerror = function() { callback("Network Error", null); }; xhr.send(); } loadFile(function(error, data) { if (error) { console.log(error); return; } console.log(data); }); ``` Fetch approach: [S1] ```javascript async function loadFile() { try { let response = await fetch("data.json"); if (!response.ok) { throw new Error("HTTP Error: " + response.status); } let data = await response.json(); console.log(data); } catch (error) { console.log(error); } } loadFile(); ``` **Callback vs Promise/async-await comparison** [S1] | Callback | Promise / async-await | |----------|----------------------| | You pass a function to run later | You wait for a promise | | Manual error-first pattern | Built-in error flow | | Can become nested | Reads like normal code | | Hard to chain steps | Easy to chain steps | **Debugging hint** If fetch is not working, check the console, then the Network tab: is the file path correct, is the status code 200, is the response JSON. Most fetch bugs are not JavaScript bugs β€” they are path and response problems. [S1] ## πŸ› οΈ 적용 사둀 (Applied in summary) The page's snippets β€” the `fetch().then(r => r.json())` chain, the `await fetch` + `response.ok` guard, and the XMLHttpRequest-vs-fetch comparison β€” are the canonical applied examples. No external project/commit applications found in the source. ## πŸ’» μ½”λ“œ νŒ¨ν„΄ (Code patterns) Recommended async/await fetch with HTTP-error guard (language: JavaScript): ```javascript async function loadData() { let response = await fetch("missing.json"); if (!response.ok) { console.log("HTTP Error:", response.status); return; } let data = await response.json(); console.log(data); } loadData(); ``` Promise-chain form: ```javascript fetch("data.json") .then(function(response) { return response.json(); }) .then(function(data) { console.log(data); }); ``` ## βš–οΈ 비ꡐ 및 선택 κΈ°μ€€ (Comparison & decision criteria) - **Callback (XMLHttpRequest)** β€” pass a function to run later; manual error-first pattern; can become nested and is hard to chain. [S1] - **Promise / async-await (fetch)** β€” wait for a promise; built-in error flow; reads like normal code and is easy to chain. Recommended for beginners. [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 Await]], [[JavaScript Promise]], [[JavaScript Async Debug]], [[JavaScript Async Callbacks]] - **μ°Έμ‘° λ§₯락:** The practical application of promises and async/await for retrieving server data. ## πŸ“š 좜처 (Sources) - [S1] W3Schools β€” JavaScript Async Fetch β€” https://www.w3schools.com/js/js_async_fetch.asp ## πŸ“ λ³€κ²½ 이λ ₯ (Change history) - 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Async Fetch" page (Astra wiki-curation, P-Reinforce v3.1 format).