SOF3 / await-generator

Write code in async/await style in PHP using generators.
https://sof3.github.io/await-generator/master/
Apache License 2.0
123 stars 15 forks source link

Cancellable interface #104

Open SOF3 opened 3 years ago

SOF3 commented 3 years ago

I don't know if "cancel" is a good term; I am not even sure if cancellation is a correct thing to do in a promise framework, where promise is just a state machine (unlike Rust futures, where you need to await a future to actually execute it).

Design

function read_line_await(LineBufReader $reader) {
    $resolve = yield Await::RESOLVE;
    $isCancelled = yield Await::IS_CANCEL;
    $reader->shiftLineCallback(function($line) use($isCancelled, $resolve) {
        if($isCancelled()) {
            $reader->unshiftLine($line);
        } else {
            $resolve($line);
        }
    });
}

When we Await::race multiple generators, the losing generators are set to be cancelled

Concerns

Coroutines are not necessarily cancellatoin-aware. They need to explicitly indicate what they do when they are cancelled (in particular, stateful promises need to reset the states they changed), which is a usability issue.