fetch-event-source icon indicating copy to clipboard operation
fetch-event-source copied to clipboard

Can it be achieved to interrupt or cancel the response during the response process

Open Pan-yongyong opened this issue 2 years ago • 4 comments
trafficstars

Can it be achieved to interrupt or cancel the response during the response process

Pan-yongyong avatar Oct 19 '23 10:10 Pan-yongyong

Do you mean cancelling an active request from the client? If so, you can provide a signal from an AbortController

cobbweb avatar Nov 07 '23 06:11 cobbweb

Do you mean cancelling an active request from the client? If so, you can provide a signal from an AbortController

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();
          }

jgarplind avatar Nov 17 '23 14:11 jgarplind

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.

cobbweb avatar Nov 20 '23 03:11 cobbweb

中断需要你在 onmessage(){ if(needStop){throw Error()} } 在 onerror(){ return err}

Gc-Peanut avatar Dec 22 '23 07:12 Gc-Peanut