Member-only story
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?
- 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', () => {
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.