@esfx/canceltoken Package
The @esfx/canceltoken
package provides the CancelToken class, an implementation of @esfx/cancelable
.
Installation
npm i @esfx/canceltoken
Usage
Basic Usage
import { CancelToken, CancelError } from "@esfx/canceltoken";
// consume a cancel token
async function doWork(token = CancelToken.none) {
// do some work
await doSomeOtherWork(token);
// throw an error if cancellation has been signaled since awaiting.
token.throwIfSignaled();
}
function doSomeOtherWork(token = CancelToken.none) {
return new Promise((resolve, reject) => {
token.throwIfSignaled(); // throw if cancellation has already been signaled.
// setup some external async operation...
const worker = createWorker();
// listen for cancellation and abort the worker.
const subscription = token.subscribe(() => {
worker.abort();
reject(new CancelError());
});
// start working, resolve when done
worker.start(resolve);
});
}
// call an async function that supports cancellation
const source = CancelToken.source();
doWork(source.token).then(
() => {
// operation completed...
source.close();
},
err => {
if (err instanceof CancelError) {
// operation was canceled.
}
});
// cancel operation after 10 seconds
setTimeout(() => source.cancel(), 1000 * 10);
Linking Tokens
import { CancelToken } from "@esfx/canceltoken";
// You can compose a cancellation graph with a root CancelToken, allowing you to cancel a large
// number of asynchronous operations all at once
let rootSource = CancelToken.source();
function cancelAllDownloads() {
// explicitly cancel all downloads
rootSource.cancel();
// reset the root source
rootSource = CancelToken.source();
}
async function downloadFile(url: string, path: string, token = CancelToken.none) {
// Get a token that times out after 60 seconds
const timeoutToken = CancelToken.timeout(60 * 1000);
// download can be canceled by either 'rootSource', 'timeoutToken' or 'token':
const linkedSource = CancelToken.source([rootSource.token, timeoutToken, token]);
const linkedToken = linkedSource.token;
// ... use linkedToken to observe cancellation.
}
Classes
CancelToken
Propagates notifications that operations should be canceled.
Interfaces
CancelSource
Signals a CancelToken when cancellation has been requested.