DEV Community

loading...

What is AbortController in Javascript?

varunprashar5
・1 min read

Do you know what is AbortConroller?

It is a Web API provided by DOM Standard.

The "AbortController" interface represents a Controller object that allows you to abort one or more Web requests as and when desired.

Properties: signal
It returns "AbortSignal" object instance to communicate with DOM request

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

Controller has one method:

controller.abort();

When you abort an async operation, the promise rejects with a DOMException named "AbortError"

Do checkout the code snippet where it is aborting the request if it takes more than 3 seconds.

//create a new AbortController object 
const controller = new AbortController();
const options = {
  method: 'POST',
  signal: controller.signal, 
  body: JSON.stringify({
    name:'Varun',
    work:'Dev'
  })
};  

// Abord the request after 3 seconds
setTimeout(() => controller.abort(), 3000);

//Send API Request to the server
fetch('/saveUser', options)
.then(response => {
  console.log(response.status);
})
.catch(error => console.error('Request Timeout'));
Enter fullscreen mode Exit fullscreen mode

So what's the other alternative? Do share in comments.

Discussion (0)