Files
2nd/10_Wiki/Topic_JavaScript/JavaScript_Async_Fetch.md
T
koriweb 9609c04755 docs(10_Wiki): W3Schools 위키화 — HTML/CSS/JavaScript(core)
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>
2026-06-23 19:21:18 +09:00

8.2 KiB

id, title, category, status, verification_status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, created_at, updated_at, review_reason, merge_history, tags, raw_sources, applied_in, github_commit
id title category status verification_status canonical_id aliases duplicate_of source_trust_level confidence_score created_at updated_at review_reason merge_history tags raw_sources applied_in github_commit
javascript-async-fetch JavaScript Async Fetch Frontend draft conceptual
fetch
fetch API
response.json
response.ok
HTTP request JavaScript
XMLHttpRequest vs fetch
B 0.89 2026-06-23 2026-06-23
javascript
js
web
frontend
w3schools
fetch
asynchronous
http
https://www.w3schools.com/js/js_async_fetch.asp

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 promisefetch() 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 recommendedasync 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 chainfetch(url).then(r => r.json()).then(data => ...). [S1]
  • async/await fetchlet 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]

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]

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]

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]

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]

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]

async function loadData() {
  let response = await fetch("data.json");
  let data = response.json();
  console.log(data);
}

Correct version: [S1]

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]

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]

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

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:

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)

📚 출처 (Sources)

📝 변경 이력 (Change history)

  • 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Async Fetch" page (Astra wiki-curation, P-Reinforce v3.1 format).