tc39 / proposal-cancelable-promises

Former home of the now-withdrawn cancelable promises proposal for JavaScript
Other
375 stars 29 forks source link

Soliciting name ideas for Promise.withCancelToken #38

Closed domenic closed 8 years ago

domenic commented 8 years ago

The most recent TC39 meeting got consensus on a helper method for adapting old APIs to use cancel tokens and cancelable promises, as in https://github.com/domenic/cancelable-promise/blob/master/New%20Ideas%20Brainstorming.md#adapting-old-apis.

My strawman name for this API is Promise.cancelable. However, this raises the old "one L versus two Ls" problem that we've so carefully avoided elsewhere. I'd love a better name.

Here's a reasonably succint description of what the method does to seed ideas: It is a factory method that creates a promise, given a promise executor in the same manner as the Promise constructor. It ties the promise to the given cancel token such that if the cancel token signals cancelation, the promise will become canceled, and additionally any cancel action returned by the executor will be run.

Right now I guess I'm liking Promise.withCancelToken.

bergus commented 8 years ago

What about simply extending the Promise constructor itself with a second, optional parameter? This especially would make it easy for subclassing.

domenic commented 8 years ago

Interesting. In general I'm not a fan of overloads with such different behavior. And this feels like a secondary convenience helper, not part of the main class construction contract. And it seems like we'd either have to do type-checking on the first argument, or put it as the second argument, which always looks weird (putting anything after a function argument).

But if other people are enthused about this, I could be convinced...

Can you explain the subclassing concern? Subclasses can still call static factory methods just fine, so I'm probably not understanding your point there.

bergus commented 8 years ago

Yes, the overloading of parameters is a bit weird, especially if the token is passed first. The idea comes from my proposal where the token was an integral "part" of every promise it races against, so it naturally had to be passed into the constructor and be available to subclasses (not being a mere factory function helper).

The big advantage of having the token available inside the promise constructor is that we can choose not to call the returned onCancel function any more after resolve or reject were called. This basically unsubscribes the cancel callback from the token as soon as there is nothing left to cancel any more, which solves the garbage collection problem that was hinted at in the meeting notes.