处理前端Pending请求:表单防重复与搜索防抖
引言
在前端开发中,网络请求的处理是日常工作中的重要部分。然而,不当的请求管理可能导致重复提交、资源浪费和用户体验下降。今天我们将深入探讨两种常见场景下的请求优化方案:表单提交防重复和搜索框防抖中断。
场景一:表单提交,服务器长时间未响应,用户需要取消请求
实现方案
const handleSubmit = async () => {
// 第以步:创建可中断的控制器
submitController.value = new AbortController()
try {
// 第二步:发起带中断信号的请求
await axios.post('/xxxx/submitForm', formData, {
signal: submitController.value.signal
})
alert('提交成功!')
} catch (error) {
// 自定义处理错误
}
}
// 用户主动中断提交
const handleCloseAxios = () => {
if (submitController.value) {
submitController.value.abort()
console.log('提交已中断')
}
}
场景二:搜索框防抖+中断策略
问题背景
搜索输入框的实时搜索功能容易产生大量冗余请求,需要取消过期请求。
请求中断实现
const searchProducts = async (query) => {
// 中断之前的搜索请求
if (searchController.value) {
searchController.value.abort('新的搜索请求')
}
// 创建新的控制器
searchController.value = new AbortController()
try {
const response = await axios.get('/api/search', {
params: { q: query },
signal: searchController.value.signal
})
searchResults.value = response.data
} catch (error) {
// 自定义处理错误
}
}

浙公网安备 33010602011771号