What is AbortController in Javascript?

varunprashar5

varunprashar5

Posted on June 9, 2021

What is AbortController in Javascript?

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.

💖 💪 🙅 🚩
varunprashar5
varunprashar5

Posted on June 9, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Mystery of Closures in JavaScript!
javascript Mystery of Closures in JavaScript!

November 23, 2024

JS Variables, Operators, Data Types
javascript JS Variables, Operators, Data Types

July 10, 2024

JS Introduction
javascript JS Introduction

July 10, 2024

JS Function, Object, String
javascript JS Function, Object, String

July 11, 2024

My first node API
javascript My first node API

March 23, 2024