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
@danharper I wrote a version that encapsulates the
AbortController
inside aPromise
so it can be used natively withasync/await
. We use it internally at the company I work at to terminate async tasks all the way through our state management into the network request and it seems to working well so far :)Let me know what you think.
https://gist.github.com/andrewcourtice/ef1b8f14935b409cfe94901558ba5594