OptionalonComplete: (success: boolean) => voidconst done = waitFor(1000,
(reason) => {
console.log(`Aborted: ${reason}`);
});
try {
runSomethingThatMightScrewUp();
done(); // Signal it succeeded
} catch (e) {
done(e); // Signal there was an error
}
// This function is called by `waitFor` if it was cancelled
const onAborted = (reason:string) => {
// 'reason' is a string describing why it has aborted.
// ie: due to timeout or because done() was called with an error
};
// This function is called by `waitFor` if it completed
const onComplete = (success:boolean) => {
// Called if we were aborted or finished succesfully.
// onComplete will be called after onAborted, if it was an error case
}
// If done() is not called after 1000, onAborted will be called
// if done() is called or there was a timeout, onComplete is called
const done = waitFor(1000, onAborted, onComplete);
// Signal completed successfully (thus calling onComplete(true))
done();
// Signal there was an error (thus calling onAborted and onComplete(false))
done(`Some error`);
The completion handler is useful for removing event handlers.
Helper function for calling code that should fail after a timeout. In short, it allows you to signal when the function succeeded, to cancel it, or to be notified if it was canceled or completes.
It does not execute or track the outcome of execution itself. Rather it's a bit of machinery that needs to be steered by your own logic.
waitFortakes a timeout, and two lifecycle functions,onAbortedandonComplete.onAbortedis called if the timeout has elapsed.onCompletewill run on either success or failure.When calling
waitForyou get back a function to signal success or failure: