← 中文资源

简体中文版本

Response.body 一次性消费与 clone 分流

response.json()/text() 只能消费一次流:bodyUsed 变 true,再读抛 TypeError;clone() 把体分给两个消费者,各自恰好读完一次。

阅读英文原文

实现说明

每个异步步骤都被 await,拒绝会在发起调用的那一行浮出。 顶层就这几处状态:response、body、response2、raw。

使用要点

  • 浏览器才是这里的运行环境:fetch 在 Node 里拿不到。
  • 跑完文件,输出里会留下标记——first read:、bodyUsed:、second read:。

常见问题

有语言之外需要解析的导入吗?

没有。每个导入都解析到语言自带的模块。 跨调用保留的状态放在这些顶层绑定里:response、body、response2。

核心语句

const [asText, asJson] = await Promise.all([response3.text(), twin.json()]);
const response2 = await fetch("https://httpbingo.org/json");
const response3 = await fetch("https://httpbingo.org/json");

代码示例

// response.json() and response.text() are one-shot: a consumed body cannot be read again.
const response = await fetch("https://httpbingo.org/json");
const body = await response.json();
console.log("first read:", body.slideshow.title);

// bodyUsed flips to true after any consume call
console.log("bodyUsed:", response.bodyUsed);

// reading again throws TypeError instead of returning empty data
try {
  await response.json();
} catch (error) {
  console.log("second read:", (error as TypeError).name);
}

// text() reads as a string; json() parses — same underlying stream
const response2 = await fetch("https://httpbingo.org/json");
const raw = await response2.text();
console.log("text length:", raw.length, "bodyUsed:", response2.bodyUsed);

// clone() forks the body so both consumers can read once each
const response3 = await fetch("https://httpbingo.org/json");
const twin = response3.clone();
const [asText, asJson] = await Promise.all([response3.text(), twin.json()]);
console.log("clone paths:", asText.length > 0, typeof asJson);