Member-only story
How to cancel a promise in JavaScript ?
Published in
3 min readOct 6, 2024

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?
- User Interaction: If a user navigates away or cancels a task, ongoing promises should not be resolved or executed.
- Performance: Canceling unnecessary promises can help improve application performance and responsiveness.
- 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', () => {…