srmagura / real-cancellable-promise

Cancellable promise library for JavaScript and TypeScript.
https://srmagura.github.io/real-cancellable-promise
MIT License
34 stars 2 forks source link

Using `CancellablePromise` with `async await` #2

Closed CMCDragonkai closed 2 years ago

CMCDragonkai commented 2 years ago

Is your feature request related to a problem? Please describe.

Is there a way to return CancellablePromise while using async await syntax?

All my existing code is using async await, and your examples all use normal functions.

Describe the solution you'd like

async function f () {
  return CancellablePromise.resolve(1);
}

There seems to be 2 problems with this:

  1. The async functions seem to always return a native promise, so it wraps it
  2. The return type of f cannot be CancellablePromise even if it implements the promise interface

Describe alternatives you've considered

If this is insurmountable, perhaps something like:

function f (): CancellablePromise {
  return wrap(async () => {
    // here I can use `await` syntax as normal
    return 1;
  });
}

Where the wrap can be used to wrap the output of the async function into a cancellable promise, and the end result is a f returning CancellablePromise.

Unfortunately this seems to require alot of refactoring if I want to do this. A wrap decorator could also work, but TS decorators can't change the return type.

srmagura commented 2 years ago

Hey @CMCDragonkai, see this example in the README. (buildCancellablePromise)