实现说明
AbortController 取消在飞请求可以归结为函数 search。
异步边界用 await 处理,失败以 rejected promise 的形式在调用点浮出,不会被静默吞掉。非法状态在入口就被拒绝:抛出 Error,而不是带着坏数据继续。
使用要点
- 这是浏览器侧代码——
fetch在 Node 里解析不到。 - 守卫
!response.ok命中后立刻用提前的throw结束这一轮。 - 每一步打印都带着自己的标签:
superseded:、first:、second:。
常见问题
输入非法时会怎样?
代码会抛出 Error——守卫条件 !response.ok 会在主逻辑之前拦下坏状态。请在调用点处理,或有意让它向上传播。
除了语言运行时还需要什么准备?
什么都不需要——语言运行时是唯一要求。 文件在加载时定义 search。
入口签名:async function search(term)
核心语句
return await response.json();
const response = await fetch('/api/search?q=' + encodeURIComponent(term), {
signal: controller.signal,
});
if (!response.ok) throw new Error('search failed: ' + response.status);
代码示例
let inFlight = null;
async function search(term) {
// 新请求前先取消上一个:避免旧响应覆盖新结果
if (inFlight) inFlight.abort();
const controller = new AbortController();
inFlight = controller;
try {
const response = await fetch('/api/search?q=' + encodeURIComponent(term), {
signal: controller.signal,
});
if (!response.ok) throw new Error('search failed: ' + response.status);
return await response.json();
} catch (error) {
if (error.name === 'AbortError') {
console.log('superseded:', term);
return null;
}
throw error;
} finally {
if (inFlight === controller) inFlight = null;
}
}
search('rea').then((r) => console.log('first:', r));
search('react').then((r) => console.log('second:', r));