Concept inspired by the CancellationTokenSource
and CancellationToken
used in C# for cancelling async functions.
import CancellationTokenSource from './CancellationTokenSource'
async function doStuff(foo, cancellationToken) {
// do stuff with foo on each significant step call:
cancellationToken.throwIfCancelled();
// for example, my use-case is uploading chunks of a file and cancelling the XHR
return ':)';
}
var cst = new CancellationTokenSource;
doStuff('eee', cst.token)
.then(result => console.log('result', result))
.catch(err => console.error('failed', err));
setTimeout(() => cst.cancel(), 1000); // auto-cancel after one second
import CancellationTokenSource from './CancellationTokenSource'
function doStuff(foo, cancellationToken) {
return new Promise((resolve, reject) => {
// do stuff with foo on each significant step call:
if (cancellationToken.isCancelled()) return reject('Cancelled');
// for example, my use-case is uploading chunks of a file and cancelling the XHR
resolve(':)');
});
}
var cst = new CancellationTokenSource;
doStuff('eee', cst.token)
.then(result => console.log('result', result))
.catch(err => console.error('failed', err));
setTimeout(() => cst.cancel(), 1000); // auto-cancel after one second
That
cancelled
property of theCancellationToken
class looks like it could be publicly set to me. So the symbol protection for thecancel()
method seems not very effective. I think that should be a private field. Or in good old days before there were classes, a variable in the function closure.But I'm going to use the
AbortController
as suggested above. Thanks anyway for providing this connection as I was looking for a CancellationToken for JavaScript. 🙂