Hilla Documentation

Cancelling Endpoint Requests

Sometimes it can be useful to programmatically cancel some requests, for example when they are taking too long or are waiting in a queue despite no longer being needed. Hilla allows developers to cancel these requests using standard AbortControllers.

All endpoint requests support an optional parameter that can be used to pass an AbortSignal which will allow them to be cancelled.

It is worth remembering that a single AbortController can be used to cancel multiple requests by passing its signal to all of them.

The following example creates two buttons: one that makes requests to a slow endpoint method, and another that triggers the cancellation of previously created requests.

If a request is subject to cancellation, errors must be handled, as the endpoint method will throw AbortError.

private abortController = new AbortController();

render() {
    return html`
        <div>
            <vaadin-button @click=${this.makeRequest}>Make a request</vaadin-button>
            <vaadin-button @click=${this.cancelRequest}>Cancel pending requests</vaadin-button>
        </div>`;
}

async makeRequest() {
    console.log("Making request");

    try {
        const serverResponse = await HelloWorldEndpoint.slow({ signal: this.abortController.signal });
        Notification.show(serverResponse);
    } catch (error: any) {
        if (error.name === 'AbortError') {
            Notification.show("Request aborted");
        } else {
            throw error;
        }
    }
}

cancelRequest() {
    console.log("Cancelling request(s)");
    this.abortController.abort();
    this.abortController = new AbortController();
}