取消fetch请求

const controller = new AbortController();
const signal = controller.signal;

// API responds after 5s
// Note the 'signal' in the second argument
fetch('https://slowmo.glitch.me/5000', { signal })
  .then(r => r.json())
  .then(response => console.log(response))
  .catch(err => {
    if (err.name === 'AbortError') {
      console.log('Fetch was aborted');
    } else {
      console.error('Oops!', err);
    }
  });


// Abort the request after 2s
// This will abort the fetch with 'AbortError'
setTimeout(() => {
  controller.abort();
}, 2000);

原文链接:
https://meetguns.com/blog/aborting-a-fetch-request/

你可能感兴趣的:(取消fetch请求)