DEV Community

Asim Khan
Asim Khan

Posted on

How to stop a Pending Promise in JavaScript (Timing Based Rejection)

In JavaScript, a promise is an object representing the eventual completion or failure of an asynchronous operation. To stop an ongoing promise, you can use the Promise.race() method to create a new promise that resolves or rejects as soon as one of the promises passed as an argument resolves or rejects. Here's an example:

// Create a new Promise that resolves after 5 seconds
const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Promise resolved!');
  }, 5000);
});

// Create a new Promise that rejects after 3 seconds
const stopPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject(new Error('Promise stopped!'));
  }, 3000);
});

// Use Promise.race() to stop the ongoing promise after 3 seconds
Promise.race([myPromise, stopPromise])
  .then(result => console.log(result)) // Will not be executed
  .catch(error => console.error(error.message)); // Will be executed after 3 seconds
Enter fullscreen mode Exit fullscreen mode

In this example, myPromise resolves after 5 seconds, but stopPromise rejects after 3 seconds. By passing these two promises to Promise.race(), we create a new promise that will either resolve with the result of myPromise or reject with the error from stopPromise, whichever happens first. In this case, stopPromise rejects after 3 seconds, causing the new promise to reject with the same error. The catch() method is then called with the error message "Promise stopped!".

Top comments (0)