Skip to content

3.2.0

Compare
Choose a tag to compare
@sebdvd sebdvd released this 10 Oct 11:08
· 1440 commits to master since this release
2255de6
  • feature: execute onCancel or finally callback when promise is canceled
import CancelablePromise from 'cancelable-promise';

const promise = new CancelablePromise((resolve, reject, onCancel) => {
  const worker = new Worker('some-script.js');

  onCancel(() => {
    worker.terminate();
  });

  worker.onmessage = (event) => resolve(event.data);
  worker.onerror = (error) => reject(error);
});

promise.cancel(); // It will execute the callback passed to onCancel
let worker;
const promise = cancelable(
  new Promise((resolve, reject) => {
    worker = new Worker('some-script.js');
    worker.onmessage = (event) => {
      resolve(event.data); // never executed
    };
    worker.onerror = (error) => {
      reject(error); // never executed
    };
  })
)
  .then(() => {
    console.log('never logged');
  })
  .finally(
    () => {
      console.log('executed');
      if (worker) {
        worker.terminate();
        worker = null;
      }
    },
    // runWhenCanceled boolean
    true
  );

promise.cancel();