Answers:
fetch
现在支持signal
截至2017年9月20日的参数,但目前并非所有浏览器都支持此参数。
2020更新:大多数主流浏览器(Edge,Firefox,Chrome,Safari,Opera和其他一些浏览器)都支持该功能,该功能已成为DOM生活标准的一部分。(截至2020年3月5日)
这是我们很快就会看到的更改,因此您应该可以使用AbortController
s 取消请求AbortSignal
。
它的工作方式是这样的:
第1步:您创建了一个AbortController
(现在我只使用了这个)
const controller = new AbortController()
步骤2:您会收到AbortController
s信号,如下所示:
const signal = controller.signal
第3步:您将传递为signal
,例如:
fetch(urlToFetch, {
method: 'get',
signal: signal, // <------ This is our AbortSignal
})
步骤4:只要需要,就中止:
controller.abort();
这是一个工作原理示例(可在Firefox 57+上运行):
<script>
// Create an instance.
const controller = new AbortController()
const signal = controller.signal
/*
// Register a listenr.
signal.addEventListener("abort", () => {
console.log("aborted!")
})
*/
function beginFetching() {
console.log('Now fetching');
var urlToFetch = "https://httpbin.org/delay/3";
fetch(urlToFetch, {
method: 'get',
signal: signal,
})
.then(function(response) {
console.log(`Fetch complete. (Not aborted)`);
}).catch(function(err) {
console.error(` Err: ${err}`);
});
}
function abortFetching() {
console.log('Now aborting');
// Abort.
controller.abort()
}
</script>
<h1>Example of fetch abort</h1>
<hr>
<button onclick="beginFetching();">
Begin
</button>
<button onclick="abortFetching();">
Abort
</button>
AbortController is not defined
。无论如何,这只是概念的证明,至少使用Firefox 57+的人可以看到它的正常运行
https://developers.google.com/web/updates/2017/09/abortable-fetch
https://dom.spec.whatwg.org/#aborting-ongoing-activities
// setup AbortController
const controller = new AbortController();
// signal to pass to fetch
const signal = controller.signal;
// fetch as usual
fetch(url, { signal }).then(response => {
...
}).catch(e => {
// catch the abort if you like
if (e.name === 'AbortError') {
...
}
});
// when you want to abort
controller.abort();
适用于Edge 16(2017-10-17),Firefox 57(2017-11-14),台式机Safari 11.1(2018-03-29),iOS Safari 11.4(2018-03-29),Chrome 67(2018-05) -29)及更高版本。
在较旧的浏览器上,可以使用github的whatwg-fetch polyfill和AbortController polyfill。您也可以检测到较旧的浏览器并有条件地使用polyfills:
import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'
import {fetch} from 'whatwg-fetch'
// use native browser implementation if it supports aborting
const abortableFetch = ('signal' in new Request('')) ? window.fetch : fetch
自2018年2月起,fetch()
可以在Chrome上使用以下代码取消(阅读使用可读流以启用Firefox支持)。不会出错catch()
,这是一个临时解决方案,直到AbortController
被完全采用为止。
fetch('YOUR_CUSTOM_URL')
.then(response => {
if (!response.body) {
console.warn("ReadableStream is not yet supported in this browser. See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream")
return response;
}
// get reference to ReadableStream so we can cancel/abort this fetch request.
const responseReader = response.body.getReader();
startAbortSimulation(responseReader);
// Return a new Response object that implements a custom reader.
return new Response(new ReadableStream(new ReadableStreamConfig(responseReader)));
})
.then(response => response.blob())
.then(data => console.log('Download ended. Bytes downloaded:', data.size))
.catch(error => console.error('Error during fetch()', error))
// Here's an example of how to abort request once fetch() starts
function startAbortSimulation(responseReader) {
// abort fetch() after 50ms
setTimeout(function() {
console.log('aborting fetch()...');
responseReader.cancel()
.then(function() {
console.log('fetch() aborted');
})
},50)
}
// ReadableStream constructor requires custom implementation of start() method
function ReadableStreamConfig(reader) {
return {
start(controller) {
read();
function read() {
reader.read().then(({done,value}) => {
if (done) {
controller.close();
return;
}
controller.enqueue(value);
read();
})
}
}
}
}
让我们来polyfill:
if(!AbortController){
class AbortController {
constructor() {
this.aborted = false;
this.signal = this.signal.bind(this);
}
signal(abortFn, scope) {
if (this.aborted) {
abortFn.apply(scope, { name: 'AbortError' });
this.aborted = false;
} else {
this.abortFn = abortFn.bind(scope);
}
}
abort() {
if (this.abortFn) {
this.abortFn({ reason: 'canceled' });
this.aborted = false;
} else {
this.aborted = true;
}
}
}
const originalFetch = window.fetch;
const customFetch = (url, options) => {
const { signal } = options || {};
return new Promise((resolve, reject) => {
if (signal) {
signal(reject, this);
}
originalFetch(url, options)
.then(resolve)
.catch(reject);
});
};
window.fetch = customFetch;
}
请记住,该代码未经测试!让我知道您是否已经测试过,但没有成功。它可能会警告您尝试覆盖JavaScript官方库中的'fetch'函数。