fetch响应体需用response.json()解析为JS对象,但它返回Promise,必须用await或.then()处理;直接赋值会得到pending状态的Promise而非数据。

fetch 请求成功后,需要用 response.json() 方法将响应体解析为 JavaScript 对象,但要注意它返回的是 Promise,必须用 await 或 .then() 处理。
为什么不能直接写 data = response.json()
response.json() 不是同步方法,它内部读取流并解析 JSON,所以返回一个 Promise。如果忽略异步特性,直接赋值,得到的会是一个 pending 状态的 Promise,而不是你想要的数据。
- ❌ 错误写法:
const data = response.json(); console.log(data); // Promise {<pending>} - ✅ 正确写法(async/await):
const data = await response.json(); - ✅ 正确写法(Promise 链):
response.json().then(data => console.log(data));
完整 fetch + json 解析示例(推荐 async/await)
这是最常用、可读性最好的方式:
async function getUser() {
try {
const response = await fetch('/api/user');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json(); // ✅ 正确:等待解析完成
console.log(data); // { id: 1, name: "Alice" }
} catch (err) {
console.error('请求失败:', err);
}
}
注意 Content-Type 和错误边界
即使状态码是 200,响应体也不一定是合法 JSON;如果后端返回空内容、HTML 错误页或非 JSON 格式,response.json() 会抛出语法错误。
- 建议先检查
response.headers.get('content-type')?.includes('application/json') - 更稳妥的做法是用
try/catch包裹await response.json() - 例如:
let data; try { data = await response.json(); } catch (e) { console.error('JSON 解析失败', e); }
不推荐的写法:嵌套 .then 或忘记 await
以下写法容易出错且难维护:
- ❌ 忘记 await:
const data = response.json(); // data 是 Promise,不是对象 - ❌ 错误嵌套:
fetch(...).then(res => res.json()).then(data => {...}).catch(...)—— 虽然能跑,但错误处理不清晰(比如网络失败和 JSON 解析失败都进同一个 catch) - ✅ 推荐统一用 async/await + 显式判断 response.ok + 单独 try/catch json 解析


















