Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a util cancel Promises #200

Closed
camsteffen opened this issue Jun 17, 2022 · 0 comments
Closed

Add a util cancel Promises #200

camsteffen opened this issue Jun 17, 2022 · 0 comments

Comments

@camsteffen
Copy link

I know I know you can't cancel a Promise. But you can create a Promise that never resolves using the Promise constructor. So my idea is to create a util that effectively cancels a Promise when the component is destroyed. Some people say that Observable is strictly better than Promise, but I would suggest that it depends on your use case. Sometimes a Promise does all you need and with less code. This utility would make Promises good enough in even more scenarios. And then you get async/await syntax.

Usage example:

const stuff = await unlessDestroyed(fetch('http://example.com/stuff'));
console.log("Fetched stuff. The component was not destroyed.");

Possible implementation:

/// Returns a new promise that resolves the same as the provided
/// promise, unless the component is destroyed first, in which
/// case the returned promise will never resolve.
function unlessDestroyed<T>(promise: Promise<T>): Promise<T> {
  return new Promise((resolve, reject) => {
    let destroyed = false;
    const destroySub = destroySubject.subscribe(() => {
      destroyed = true;
    });

    function finish<U>(callback: (u: U) => void) {
      return (data: U) => {
        destroySub.unsubscribe();
        if (!destroyed) {
          callback(data);
        }
      };
    }
    promise.then(finish(resolve), finish(reject))
  });
}
@ngneat ngneat locked and limited conversation to collaborators Jun 21, 2022
@NetanelBasal NetanelBasal converted this issue into discussion #203 Jun 21, 2022

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant