Dev Genius

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

Follow publication

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', () => {
clearTimeout(timeoutId);
reject(new Error('Fetch aborted'));
});
});
}
const controller = new AbortController();
const signal = controller.signal;
// Start fetching data
fetchData('https://api.example.com/data', signal)
.then(data => console.log(data))
.catch(err => console.error(err.message));
// Simulate canceling the fetch after 1 second
setTimeout(() => {
controller.abort();
}, 1000);

Explanation:

  • The fetchData function simulates an asynchronous operation using a promise.
  • An AbortController is created, and its signal is passed to the promise.
  • If the controller is aborted, the promise is rejected with an appropriate error message.
  • In this example, the fetch operation is canceled after 1 second.

2. Using a Custom Cancellation Token

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in Dev Genius

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

Responses (3)

Write a response