RationalJS / future

A Js.Promise alternative for ReasonML
213 stars 15 forks source link

RFC: Test implementation of cancellation #48

Closed bloodyowl closed 2 years ago

bloodyowl commented 4 years ago

Hi! I started experimenting on cancellation with this repository as an heavy inspiration: https://github.com/bloodyowl/reason-future

The main idea is that Future.make lets you return a cancellation function:

let delay x => Future.make(resolve => {
  let timeoutId = Js.Global.setTimeout(() => resolve(), x);
  Some(() => Js.Global.clearTimeout(timeoutId));
});

Then you can cancel future directly:

let wait = delay(100);
Future.cancel(wait);

For convenience, map and flatMap by default "propagates" the cancellation:

let wait = delay(100)
  ->Future.flatMap(() => delay(100))
  ->Future.map(() => 1);

Future.cancel(wait); // Cancels up to the original delay(100);

You could however choose not to propagate the cancellation:

let wait = delay(100)
  ->Future.flatMap(~propagateCancel=false, () => delay(100))
  ->Future.map(~propagateCancel=false, () => 1);

Future.cancel(wait); // Only cancels the last Future.map;

Would a PR to this repository with this implementation be of any interest to you?

briangorman commented 4 years ago

Hi @bloodyowl, I think this is a good idea and I would welcome a PR

bloodyowl commented 4 years ago

@briangorman Opened a PR here: https://github.com/RationalJS/future/pull/52