fetch-event-source
fetch-event-source copied to clipboard
Can it be achieved to interrupt or cancel the response during the response process
Can it be achieved to interrupt or cancel the response during the response process
Do you mean cancelling an active request from the client? If so, you can provide a signal from an AbortController
Do you mean cancelling an active request from the client? If so, you can provide a
signalfrom anAbortController
You don't happen to have an example of this working by any chance?
I understand that this is default fetch functionality that is supposedly not impacted by this library, but for me, providing the signal seems to have no impact, so I had to resort to checking for it in onopen like so:
async onopen(response) {
// throw AbortError manually to force abort.
if (ctrl.signal.aborted) {
throw new AbortError();
}
It was pretty straight forward for me. My actual code is too complicated for a simple example but it boils down to something like:
const abortController = new AbortController()
fetchEventSource(someUrl, {
signal: abortController.signal,
onmessage(ev) {
const data = JSON.parse(ev.data) as MyData;
console.log(data);
},
})
abortController.abort(); // this should cancel & close your request
If you're using React.js or similar, make sure you've got the same abortController instance reference.
中断需要你在 onmessage(){ if(needStop){throw Error()} } 在 onerror(){ return err}