如何在 Raku 中超时承诺? [英] How can I timeout a promise in Raku?

查看:44
本文介绍了如何在 Raku 中超时承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以安排一个 Promise 在给定的时间内保持

I know I can schedule a Promise to be kept in a given amount of time with

my $promise = Promise.in($seconds);

但是我如何安排它被破坏?具体来说,我正在考虑一个会超时"的承诺,这样它就可以保留一定的时间,否则就会失败.

but how can I schedule it to be broken? Specifically, I'm thinking of a promise that will "timeout", so that it has up to a certain amount of time to be kept or else it will fail.

我可以用另一个 Promise 来做到这一点,就像这样:

I can do this with another Promise, like so:

my $promise = Promise.new;
...
Promise.in($seconds).then: { $promise.break };

但这感觉有点……浪费.有没有更好的方法来做到这一点?

But this feels a bit ... wasteful. Is there a better way to do this?

推荐答案

一个常见的模式是这样写:

A common pattern is to write something like this:

await Promise.anyof($the-promise, Promise.in(10));
if $the-promise {
    # it finished ahead of the timeout
}
else {
    # it timed out
}

这并没有表现为一个坏掉的 Promise,尽管这并不全是坏事(因为无论如何在很多情况下你需要区分取消和错误,所以你仍然需要做一些匹配异常类型).这种分解还有一个优点,即 $the-promise 不必是您可以保留/中断的.

That doesn't manifest itself as a broken Promise, though that's not all bad (since you need to distinguish cancellation vs. error in many cases anyway, so you'd still have to do some matching on exception type). This factoring also has the advantage that $the-promise does not have to be one that you have access to keep/break.

也可以用这样的方式来总结:

One could also wrap this up in something like this:

class TimedOut is Exception {}
sub timeout($promise, $time) {
    start {
        await Promise.anyof($promise, Promise.in($time));
        $promise ?? await($promise) !! die(TimedOut.new)
    }
}

这将再次与任何 $promise 一起工作,传递结果或异常,否则抛出超时异常.

Which will again work with any $promise, pass on the result or exception, and throw a timed-out exception otherwise.

所有这些都需要记住的是,它们实际上不会影响正在进行的工作的任何取消.这可能无关紧要,也可能很重要.如果是后者,您可能需要:

The thing to keep in mind with all of these is that they don't actually effect any cancellation of work in progress. That may not matter, or it might be important. If the latter, you'll probably want either:

  • 一个Promise,你用来传达取消已经发生;您在取消时保留它,并在将执行取消的代码中对其进行轮询
  • 考虑使用 Supply 范式,其中存在取消模型(关闭水龙头).
  • A Promise that you use to convey cancellation having taken place; you keep it when cancelling, and poll it in the code that will do the cancellation
  • To look at using the Supply paradigm instead, where there is a cancellation model (closing the tap).

这篇关于如何在 Raku 中超时承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆