Expand description
interface SerialConstructor<TFn> {
fn: (checkCancel: CheckCancelFn, current: bigint) => TFn;
onCancel?: SerialEventCancelCallback;
}Properties§
§§
fn: { ... }Function creator that returns the async function to be wrapped
on Cancel?: SerialEventCancelCallbackOptional callback to be called when the event is cancelled
This is guaranteed to be only called at most once per execution
Options for
serialfunctionserialis an async event wrapper that is cancelled when a new one starts. When a new event is started, the previous caller will receive a cancellation error, instead of being hung up indefinitely.If you want every caller to receive the latest result instead of a cancellation error, use
latestinstead.Example
Passing in arguments
TypeScript magic is used to ensure full type-safety when passing in arguments.
Getting the current serial number
The serial number has type
bigintand is incremented every timerunis called.You can have an extra argument after
checkCancel, that will receive the current serial number, if you need it for some reason.Checking for cancel
It's the event handler's responsibility to check if the event is cancelled by calling the
checkCancelfunction. This function will throw if the event is cancelled, and the error will be caught by the wrapper and returned as anErrNote that even if you don't check it, there is one final check before the result is returned. So you will never get a result from a cancelled event. Also note that you only need to check after any
awaitcalls. If there's noawait, everything is executed synchronously, and it's theoretically impossible to cancel the event. However, this depends on the runtime's implementation of promises.Handling cancelled event
To check if an event is completed or cancelled, simply
awaiton the promise check theerrYou can also pass in a callback to the constructor, which will be called when the event is cancelled. The cancel callback is guaranteed to only fire at most once per run
Exception handling
If the underlying function throws, the exception will be re-thrown to the caller.