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'));
So what's the other alternative? Do share in comments.
Top comments (0)