提问者:小点点

有没有办法在尖块结束前离开它?


例如:

$supply.tap: -> $message {
    return unless server-is-alive( );   # forbidden!
    send-to-server( $message );
}

我知道我可以。"。点击:订阅($消息){返回除非…;#作品!}"。但是我想知道是否有任何与块相关的控制流可以简单地中断它。


共2个答案

匿名用户

目前,没有这样的机制。但是,有人建议可以有一个离开,它可以执行您的请求。

使用Supply时,通常最好使用供应/react/无论何时语法。如果使用它,还有另一种解决方案:由于无论何时都是异步循环构造,那么可以编写:

whenever $supply -> $message {
    next unless server-is-alive( );
    send-to-server( $message );
}

这里的next意味着跳过块的其余部分。

匿名用户

返回CONTROL异常

-> {
  return 42
}();

CONTROL {
  default {
    .^name.say; # CX::Return
  }
}

您可以将块包装在具有CONTROL块的东西中,或者包装在已经处理CX::返回的东西中,例如sub

my &c = ->{
  return 42
}

sub {
  c(); # call it

  say 'never gets here';
}().say; # call it and say the result of `return`

我认为next在水龙头上使用会更有意义。

$supply.tap: -> $message {
    next unless server-is-alive( );
    send-to-server( $message );
}

这目前不起作用。

不管怎样,你为什么不使用更好的[react|供应]

react whenever $supply -> $message {
    next unless server-is-alive( );
    send-to-server( $message );
}

请注意,它将阻塞当前线程,以获取它,这样它就不会将start添加到前面。

测试代码:

# setup some messages
my $supply = Supply.interval(0.1).map: {
  .Str.uninames.join(' ' x 4);
}

react {
  my $server-is-alive = True;
  sub server-is-alive (){ $server-is-alive }

  sub send-to-server ( $message ){
     say $message
  }

  whenever Supply.interval( 0.5 ) {
    $server-is-alive = !$server-is-alive;
    say "server is { 'not ' x !$server-is-alive }alive";
  }

  # here is your code
  whenever $supply -> $message {
      next unless server-is-alive( );
      send-to-server( $message );
  }

  whenever Promise.in(3) {
    done
  }
}

这导致

server is not alive
server is alive
DIGIT FIVE
DIGIT SIX
DIGIT SEVEN
DIGIT EIGHT
DIGIT NINE
server is not alive
server is alive
DIGIT ONE    DIGIT FIVE
DIGIT ONE    DIGIT SIX
DIGIT ONE    DIGIT SEVEN
DIGIT ONE    DIGIT EIGHT
DIGIT ONE    DIGIT NINE
server is not alive
server is alive
DIGIT TWO    DIGIT FIVE
DIGIT TWO    DIGIT SIX
DIGIT TWO    DIGIT SEVEN
DIGIT TWO    DIGIT EIGHT
DIGIT TWO    DIGIT NINE
server is not alive