Search code examples
promiserakurakudo

Why am I not allowed to break a Promise?


The following simple Promise is vowed and I am not allowed to break it.

my $my_promise = start {
    loop {}   # or sleep x;
    
    'promise response'
}

say 'status : ', $my_promise.status;      # status : Planned

$my_promise.break('promise broke');       # Access denied to keep/break this Promise; already vowed
                                          # in block <unit> at xxx line xxx

Why is that?


Solution

  • Because the Promise is vowed, you cannot change it: only something that actually has the vow, can break the Promise. That is the intent of the vow functionality.

    What are you trying to achieve by breaking the promise as you showed? Is it to stop the work being done inside of the start block? Breaking the Promise would not do that. And the vow mechanism was explicitly added to prevent you from thinking it can somehow stop the work inside a start block.

    If you want work inside a start block to be interruptible, you will need to add some kind of semaphore that is regularly checked, for instance:

    my int $running = 1;
    my $my_promise = start {
        while $running {
            # do stuff
        }
        $running
    }
    
    # do other stuff
    $running = 0;
    await $my_promise;
    

    Hope this made sense.