[英]How do I abort fetch request and start a new one immediately?
Here's an example from MDN below. 下面是来自MDN的示例。 There are two buttons. 有两个按钮。 One is sending a request and another is canceling. 一个正在发送请求,另一个正在取消。
var controller = new AbortController();
var signal = controller.signal;
var downloadBtn = document.querySelector('.download');
var abortBtn = document.querySelector('.abort');
downloadBtn.addEventListener('click', fetchVideo);
abortBtn.addEventListener('click', function() {
controller.abort();
console.log('Download aborted');
});
function fetchVideo() {
...
fetch(url, {signal}).then(function(response) {
...
}).catch(function(e) {
reports.textContent = 'Download error: ' + e.message;
})
}
Now my case is different. 现在我的情况有所不同。 I have a query
parameter and if fetching is in progress but not finished and query
parameter changes - how do I send a new request automatically canceling previous one? 我有一个query
参数,如果正在进行获取但未完成,并且query
参数已更改-如何发送新请求以自动取消上一个请求?
Not sure if I got it clearly, but from what I understand, your case is not different no. 不知道我能否清楚地知道,但据我了解,您的情况没有不同。
The basics are the same, store the controller somewhere accessible to your logic that may cancel it, and cancel it if needed, before sending the new request: 基本原理是相同的,将控制器存储在您的逻辑可访问的位置,该逻辑可以取消它,并在发送新请求之前根据需要取消它:
let aborter = null; // make the aborter accessible function getData(param) { // cancel pending request if any if(aborter) aborter.abort(); // make our request cancellable aborter = new AbortController(); const signal = aborter.signal; const url = 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png?rand=' + param; return fetch(url, {signal}) // clean up, not really needed but may help to know if there is a pending request .then(r => {aborter = null; return r;}) } // first request will get aborted getData("foo") .then(r => console.log('foo done')) .catch(e => console.error('foo failed', e.name, e.message)); // will abort the previous one getData("bar") .then(r => console.log('bar done')) .catch(e => console.error('bar failed', e.name, e.message))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.