Cancel Promise pattern (no cancellable promises)

Jan-Ivar Bruaroey jib at mozilla.com
Mon Oct 31 16:29:01 UTC 2016


On 10/28/16 8:39 AM, Bergi wrote:
> Jan-Ivar Bruaroey wrote:
>> If you try the fiddle - http://jsfiddle.net/jib1/jz33qs32/ - you'll see
>> cancelling terminates the chain. If you intersperse non-cancellable
>> operations, there'd be a delay if cancel is detected during those.
>
> Yes, that's what I mean. Sure, I could use `Promise.race` to get the 
> cancellation even if the non-cancellable operation resumes, but that's 
> quite ugly:
>
> Promise.race([
>     promise()
>     …chain…,
>     cancelToken
> ]).then(callback);
>
> especially when you'll need to nest that pattern.

To be clear, the non-cancellable operation won't "resume" in the face of 
a CancelledError. Only if the cancel happened to trigger during one of 
the non-cancellable actions would there be a slight delay until that 
non-cancellable operation finished (which I consider a feature) and if a 
cancellable operation follows it, cancellation will happen at that point.

In someone can't tolerate that, then Promise.race is well-defined to do 
exactly what you show, and works in harmony with this pattern. Why 
reinvent the wheel?

And you'd Promise.race against the entire chain, so no need to nest this 
pattern typically. This is what I mean with focusing on the minimal 
use-case. Most people just want us to solve fetch already, so that 
expensive network resources can be freed. To get out of the current 
inertia, why not define:

     fetch (url, { cancelPromise: token })

now and use this pattern, and leave the more desirable { cancel } name 
for whatever future invention we hope will replace it (or annex it if 
nothing better materializes)?

.: Jan-Ivar :.



More information about the es-discuss mailing list