写过 AI 流式响应的都踩过这个坑——Safari 27 今天把它彻底原生化了
写过 AI 流式响应的都踩过这个坑:fetch 拿回来一个 Response,body 是个 ReadableStream,要套一层 TextDecoderStream,再起一个 while 循环调 reader.read(),解析 SSE 分隔符,buffer 不完整还要留着下次拼上——这套样板代码每个 AI 项目都要写一遍。
Safari 27 把这件事彻底原生化了。
现在 Response.body 直接是 async iterable,整个流可以直接 for await…of 遍历:
// 旧写法
const response = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages }),
});
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
process.stdout.write(value);
}
// 新写法
const res = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages }),
});
for await (const chunk of res.body) {
const text = new TextDecoder().decode(chunk);
process.stdout.write(text);
}
代码少了两层嵌套。这不是语法糖——Response.body 本身现在实现了 async iterable 协议。
为什么这和 AI 编程高度相关
主流 AI API(OpenAI Responses API、Anthropic Streaming、OpenRouter 等)都返回 SSE 流,for await…of 拿到的是最原始的字节块:
const stream = await openai.responses.create({
model: 'gpt-5',
input: '解释量子计算',
stream: true,
});
for await (const event of stream) {
if (event.type === 'response.output_text.delta') {
document.getElementById('output').textContent += event.delta;
}
}
少了 stream.getReader() 这一步,也不需要自己维护 reader 生命周期。
一个容易踩的坑:SSE 帧解析要自己做
for await…of 给的是传输层 chunk,不是 SSE 事件。需要自己按 SSE 协议解析:
for await (const raw of res.body) {
const lines = new TextDecoder().decode(raw).split('
')
.filter(line => line.startsWith('data: '))
.map(line => line.slice(6));
for (const data of lines) {
if (data === '[DONE]') continue;
try { handleEvent(JSON.parse(data)); } catch {}
}
}
浏览器兼容性:Safari 27 刚进 Baseline
| 浏览器 | 版本 | 状态 |
|---|---|---|
| Safari | 27+ | ✅ 刚进 Baseline |
| Chrome | 124+ | ✅ |
| Firefox | 110+ | ✅ |
| Edge | 124+ | ✅ |
Chrome 和 Firefox 早就支持了,只是 Safari 一直缺着,Safari 27 补上缺口后全球覆盖率正式达标。
下一步
写一个带渐进增强的封装:
async function* streamAI(url, payload) {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
if (res.body[Symbol.asyncIterator]) {
for await (const chunk of res.body) {
yield new TextDecoder().decode(chunk);
}
} else {
// 降级逻辑
}
}
res.body[Symbol.asyncIterator] 有值就说明可以用 for await…of,渐进增强成本几乎为零。
评论区
0 条评论
登录后可评论。