有一个新的接口用于从JavaScript发出请求:fetch()
。有没有内置的机制来取消这些正在进行中的请求?
发布于 2017-10-17 16:03:18
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)、desktop safari 11.1 (2018-03-29)、ios safari 11.4 (2018-03-29)、chrome 67 (2018-05-29)及更高版本。
在较旧的浏览器上,您可以使用github's whatwg-fetch polyfill和AbortController polyfill。你也可以使用detect older browsers and use the polyfills conditionally:
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-02-23 00:53:36
从2018年2月起,在Chrome上可以使用以下代码取消fetch()
(请阅读Using Readable Streams以启用对火狐的支持)。在完全采用AbortController
之前,不会抛出任何错误供catch()
拾取,这是一个临时解决方案。
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();
})
}
}
}
}
发布于 2017-09-13 02:17:00
正如@spro所说,目前还没有合适的解决方案。
但是,如果您有正在进行的响应,并且正在使用ReadableStream,则可以关闭流以取消请求。
fetch('http://example.com').then((res) => {
const reader = res.body.getReader();
/*
* Your code for reading streams goes here
*/
// To abort/cancel HTTP request...
reader.cancel();
});
https://stackoverflow.com/questions/31061838
复制相似问题