DEV Community

Cancellable async functions in JavaScript

Sam Thorogood on July 11, 2018

(This post explains how to use generators to wrangle duplicate calls to async functions. Check out this gist for the final approach or read on to l...
Collapse
 
getify profile image
Kyle Simpson

The solution presented here isn't really "cancellation", because (as the article acknowledges), the async..await function (aka, the generator) isn't stopped right away, but only silently exits later after it eventually resumes (if ever).

A better approach, IMO, is to proactively stop the generator (using its return() or throw() methods) right away.

CAF is a library I wrote to make such truyly-cancelable async functions easy to write and work with: github.com/getify/CAF

Collapse
 
jayfranko2 profile image
Jay Franko • Edited

Great post!! For my 10 line function approach #2 suffices, but the final solution will sure come in handy some day!

By the way: in my case the barrier check is in a deeper nested function. I throw an error instead of a simple return. That way I can suffice with only a single barrier check instead of 5.

Collapse
 
simevidas profile image
Šime Vidas

When I read nonce, my first thought was a library for that, but no, just new Object() 😄

Collapse
 
samthor profile image
Sam Thorogood

Ever-increasing numbers also works but I think an arbitrary Object makes the most sense :)