-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0adcdec
commit ea39905
Showing
2 changed files
with
70 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
/** | ||
* A CancelToken should be passed to cancelable functions. Those functions should then check the state of the | ||
* token and return early, or use checkCanceled to throw a CanceledError if the token has been canceled. Callers | ||
* of cancelable functions should catch CanceledError. | ||
*/ | ||
export interface CancelToken { | ||
readonly canceled: boolean; | ||
checkCanceled: () => void; | ||
} | ||
|
||
/** | ||
* Indicates that the function was canceled by a call to the cancellation token's cancel function. | ||
*/ | ||
export class CanceledError extends Error { | ||
constructor() { | ||
super('canceled'); | ||
this.name = 'CanceledError'; | ||
} | ||
} | ||
|
||
/** | ||
* Returns a cancel token and a cancellation function. The token can be passed to functions and checked | ||
* to see whether it has been canceled. The function can be called to cancel the token. | ||
*/ | ||
export function withCancel(): [CancelToken, () => void] { | ||
let isCanceled = false; | ||
return [ | ||
{ | ||
get canceled() { | ||
return isCanceled; | ||
}, | ||
checkCanceled() { | ||
if (isCanceled) { | ||
throw new CanceledError(); | ||
} | ||
}, | ||
}, | ||
() => (isCanceled = true), | ||
]; | ||
} |