Member-only story

How to cancel a promise in JavaScript ?

Pravin M
Dev Genius
Published in
3 min readOct 6, 2024
How to cancel a promise in JavaScript ?
How to cancel a promise in JavaScript ?

If you’re on a free Medium plan, click here to read — Free Access

For more questions and answers visit our website at Frontend Interview Questions

Why Cancel a Promise?

  1. User Interaction: If a user navigates away or cancels a task, ongoing promises should not be resolved or executed.
  2. Performance: Canceling unnecessary promises can help improve application performance and responsiveness.
  3. Resource Management: Prevent resource-intensive operations that are no longer needed.

Approaches to Canceling a Promise

1. Using an AbortController

The AbortController is a built-in feature in JavaScript that allows you to abort fetch requests and other asynchronous operations. While not specifically designed for promises, it can be leveraged to control asynchronous tasks that rely on promises.

Example:

// Function to simulate an asynchronous operation
function fetchData(url, signal) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
resolve(`Data from ${url}`);
}, 2000);
// Handle abort signal
signal.addEventListener('abort', () => {…

--

--

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Responses (1)