cancel a promise in javascript

To cancel a promise in JavaScript and prevent it from resolving, we can use the AbortController and AbortSignal APIs introduced in ES2018.

Here's an example of how to use the AbortController to cancel a promise:

index.tsx
const controller = new AbortController();
const signal = controller.signal;

const myPromise = new Promise((resolve, reject) => {
  // Do some async operation here
  // ...

  // Check if the promise is cancelled
  if (signal.aborted) {
    // If cancelled, reject the promise with an AbortError
    return reject(new DOMException('Aborted', 'AbortError'));
  }

  // Once the async operation completes, resolve the promise
  resolve('Result of async operation');
});

// Cancel the promise after 5 seconds
setTimeout(() => {
  controller.abort();
}, 5000);

try {
  const result = await myPromise;
  console.log(result);
} catch (error) {
  if (error.name === 'AbortError') {
    console.log('Promise was cancelled.');
  } else {
    console.error(error);
  }
}
763 chars
33 lines

In this example, we create an AbortController and get its associated AbortSignal. We then create a new promise, which checks if the AbortSignal has been aborted before resolving or rejecting the promise.

We also set a timeout to cancel the promise after 5 seconds using controller.abort(), which sends an abort signal to the promise.

Finally, we use await to wait for the promise to either resolve or reject, and handle any AbortError by logging a message to the console.

gistlibby LogSnag