CancelablePromise.ts 605 B

12345678910111213141516171819202122
  1. // https://github.com/facebook/react/issues/5465
  2. export interface CancelablePromise<T> {
  3. promise: Promise<T>;
  4. cancel: () => void;
  5. }
  6. export const makePromiseCancelable = <T>(promise: Promise<T>): CancelablePromise<T> => {
  7. let hasCanceled_ = false;
  8. const wrappedPromise = new Promise<T>((resolve, reject) => {
  9. promise.then((val) => (hasCanceled_ ? reject({ isCanceled: true }) : resolve(val)));
  10. promise.catch((error) => (hasCanceled_ ? reject({ isCanceled: true }) : reject(error)));
  11. });
  12. return {
  13. promise: wrappedPromise,
  14. cancel() {
  15. hasCanceled_ = true;
  16. },
  17. };
  18. };