Abort a fetch

Gao

Since fetch is introduced in browser has passed nearly one decade. But in the beginning, it does no have a method to cancel request. AbortController is the solution to abort a request send by fetch.

AbortController use an AbortSignal to cancel fetch request.

The demo code:

const controller = new AbortController(); const signal = controller.signal; const url = "video.mp4"; const downloadBtn = document.querySelector(".download"); const abortBtn = document.querySelector(".abort"); downloadBtn.addEventListener("click", fetchVideo); abortBtn.addEventListener("click", () => { const reason = 'User cancel download by click the cancel button'; controller.abort(reason); console.log("Download aborted"); }); function fetchVideo() { fetch(url, { signal }) .then((response) => { console.log("Download complete", response); }) .catch((err) => { console.error(`Download error: ${err.message}`); }); }
  • Note:

When abort() is called, the fetch() promise rejects with an Error of type DOMException, with name AbortError.