Function waitFor

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.

waitFor takes a timeout, and two lifecycle functions, onAborted and onComplete. onAborted is called if the timeout has elapsed. onComplete will run on either success or failure.

waitFor(1000, 
(error) => {
// Failed
},
(success) => {
if (success) {
// Succeeded
}
});

When calling waitFor you get back a function to signal success or failure:

const done = waitFor(1000, onAborted, onComplete);
done(); // No parameters signals success
done('failed'); // A string parameter indicates failure
const 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.

  • Parameters

    • timeoutMs: number
    • onAborted: ((reason: string) => void)
        • (reason): void
        • Parameters

          • reason: string

          Returns void

    • OptionalonComplete: ((success: boolean) => void)
        • (success): void
        • Parameters

          • success: boolean

          Returns void

    Returns ((error?: string) => void)

      • (error?): void
      • Parameters

        • Optionalerror: string

        Returns void