w3resource

Cancelable Promises in JavaScript with Practical Examples


Cancelable Promise:

Write a JavaScript function that creates a cancellable Promise by using a custom wrapper.

Solution-1:

Code:

// Function to create a cancellable Promise
function createCancelablePromise(executor) {
  let cancel;

  const promise = new Promise((resolve, reject) => {
    cancel = () => reject(new Error('Promise cancelled')); // Define cancel function
    executor(resolve, reject);
  });

  promise.cancel = cancel; // Attach cancel function to the promise
  return promise;
}

// Example usage of the cancellable Promise
const cancellable = createCancelablePromise((resolve) => {
  setTimeout(() => resolve('Operation completed!'), 5000); // Simulates an async task
});

cancellable.then(console.log).catch(console.error); // Handle resolution or rejection

setTimeout(() => {
  cancellable.cancel(); // Cancel the promise after 2 seconds
}, 2000);

Output:

[object Error] { ... }

Explanation:

  • 'createCancelablePromise' wraps a promise and provides a 'cancel' method.
  • The 'cancel' method rejects the promise with a custom error message.
  • The example demonstrates cancelling the promise before it resolves.

Solution-2:

Code:

// Function to create a cancellable Promise with a flag
function createFlaggedCancelablePromise(executor) {
  let isCancelled = false; // Cancellation flag

  const promise = new Promise((resolve, reject) => {
    executor(
      (value) => {
        if (isCancelled) {
          reject(new Error('Promise cancelled'));
        } else {
          resolve(value);
        }
      },
      reject
    );
  });

  promise.cancel = () => {
    isCancelled = true; // Set the cancellation flag
  };

  return promise;
}

// Example usage of the flagged cancellable Promise
const flaggedCancellable = createFlaggedCancelablePromise((resolve) => {
  setTimeout(() => resolve('Task finished!'), 5000); // Simulates an async task
});

// Handle resolution or rejection
flaggedCancellable
  .then(console.log) // Log resolved value
  .catch((error) => console.error(error.message)); // Log the error message explicitly

// Cancel the promise after 2 seconds
setTimeout(() => {
  flaggedCancellable.cancel();
}, 2000);

Output:

"Promise cancelled"

Explanation:

  • 'createFlaggedCancelablePromise' uses a flag to track cancellation state.
  • If the flag is set to true, the promise rejects when attempting to resolve.
  • The example demonstrates cancelling the promise before it resolves.

See the Pen promises-and-async-await-exercise-18 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Simulate a Loading Spinner for Async Operations in JavaScript.
Next: Optimize API Fetching: Parallel vs Sequential Methods Explained.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.