JS Coding Questions Logo
JS Coding Questions
#386💼 Interview💻 Code

How to cancel a fetch request

Advertisement

728x90

Until a few days back, One shortcoming of native promises is no direct way to cancel a fetch request. But the new AbortController from js specification allows you to use a signal to abort one or multiple fetch calls.

The basic flow of cancelling a fetch request would be as below,

1. Create an AbortController instance

2. Get the signal property of an instance and pass the signal as a fetch option for signal

3. Call the AbortController's abort property to cancel all fetches that use that signal

For example, passing the same signal to multiple fetch calls will cancel all requests with that signal,

javascript
1const controller = new AbortController();
2
3const { signal } = controller;
4
5fetch("http://localhost:8000", { signal })
6  .then((response) => {
7  console.log(`Request 1 is complete!`);
8  })
9  .catch((e) => {
10  if (e.name === "AbortError") {
11  // We know it's been canceled!
12  }
13  });
14
15fetch("http://localhost:8000", { signal })
16  .then((response) => {
17  console.log(`Request 2 is complete!`);
18  })
19  .catch((e) => {
20  if (e.name === "AbortError") {
21  // We know it's been canceled!
22  }
23  });
24
25// Wait 2 seconds to abort both requests
26
27setTimeout(() => controller.abort(), 2000);

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 44

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
386of476