1. 使用fetch api 和 abortcontroller
现代浏览器支持fetch
api,并且提供了一个abortcontroller
接口来中止请求。
const controller = new abortcontroller(); const signal = controller.signal; fetch('/some/api/endpoint', { signal }) .then(response => { if (response.ok) { return response.json(); } else { throw new error('network response was not ok'); } }) .catch(error => { if (error.name === 'aborterror') { console.log('fetch aborted'); } else { console.error('fetch error:', error); } }); // 在需要中止请求的时候调用 controller.abort();
在这个例子中,abortcontroller创建了一个信号对象signal,它被传递给fetch请求的options对象。当调用controller.abort()时,请求会被中止,并且fetch的promise会被拒绝,抛出一个aborterror。
2. 使用xmlhttprequest 和 abort 方法
对于较老的代码或需要更细粒度控制的场景,可能正在使用xmlhttprequest。
const xhr = new xmlhttprequest(); xhr.open('get', '/some/api/endpoint', true); xhr.onreadystatechange = function () { if (xhr.readystate === 4) { if (xhr.status === 200) { console.log(xhr.responsetext); } else { console.error('request failed:', xhr.statustext); } } }; xhr.send(); // 在需要中止请求的时候调用 xhr.abort();
在这个例子中,xhr.abort()
方法会立即中止请求。如果请求已经完成(即readystate
已经是4),则调用abort()
不会有任何效果。
3. 使用第三方库(如axios)
如果使用的是像axios这样的第三方http客户端库,它通常也提供了中止请求的功能。
const canceltoken = axios.canceltoken; const source = canceltoken.source(); axios.get('/some/api/endpoint', { canceltoken: source.token }).catch(function (thrown) { if (axios.iscancel(thrown)) { console.log('request canceled', thrown.message); } else { // 处理错误 } }); // 在需要中止请求的时候调用 source.cancel('operation canceled by the user.');
在这个例子中,canceltoken用于创建一个可以取消请求的令牌。当调用source.cancel()时,请求会被中止,并且promise会被拒绝,抛出一个包含取消信息的错误。
总结
中止网络请求的能力对于提高web应用的性能和用户体验非常重要。现代浏览器和http客户端库通常都提供了相应的api来实现这一功能。
发表评论