5
0
mirror of https://github.com/wailsapp/wails.git synced 2025-05-08 03:51:15 +08:00
wails/v3/examples/cancel-async
2025-04-25 20:51:34 +10:00
..
assets Initial Windows testing completed. 7 issues. 2025-04-25 20:51:34 +10:00
main.go Add cancellation examples 2025-02-25 03:33:24 +01:00
README.md Initial Windows testing completed. 7 issues. 2025-04-25 20:51:34 +10:00
service.go Initial Windows testing completed. 7 issues. 2025-04-25 20:51:34 +10:00

Binding Call Cancelling Example

Sometimes, we need to execute functions that become long-running processes. In Go, we normally use context to cancel such processes but how can we achieve this in Javascript?

Automatically, that's how!

If your Service method's first parameter is a context.Context, then the bindings generator will generate a "cancellable promise". This allows you to specify the signal to cancel the request.

This method:

    func (*Service) LongRunning(ctx context.Context, milliseconds int) error {
        select {
        case <-time.After(time.Duration(milliseconds) * time.Millisecond):
            return nil
        case <-ctx.Done():
            return ctx.Err()
        }
    }

can be called, and cancelled, from the frontend using the following semantics:

    controller = new AbortController();
    
    try {
        await Service.LongRunning(duration).cancelOn(controller.signal);
        document.getElementById("result").innerText = "Long running call complete!";
    } catch (err) {
        document.getElementById("result").innerText = (err instanceof CancelError)
            ? "Call cancelled: " + err.cause
            : "Call failed: " + err;
    } finally {
        lastCall = null;
    }

This may now be cancelled at any time using:

controller.abort("cancel button pressed!");

Notes

To regenerate bindings, run wails3 generate bindings -clean -b -d assets/bindings in this directory.