role APlus {
method andthen(&block) {
$.then: -> Promise $p {
return Promise.break: $p.cause unless $p.status ~~ Broken;
my \res = block $p.result;
do if res ~~ Awaitable {
await res
} else {
res
}
}
}
method orcatch(&block) {
$.then: -> Promise $p {
return Promise.kept: $p.result unless $p.status ~~ Broken;
my \res = block $p.result;
do if res ~~ Awaitable {
await res
} else {
die res
}
}
}
}
sub a-start(&block) { (start block) does APlus }
sub run-something {
a-start {
die "some error" if rand > 0.5;
42
}
}
sub run-and-retry(UInt :$try = 1) {
run-something.orcatch: -> $err {
die $err if $try > 5;
say "retry";
run-and-retry :try($try + 1)
}
}
say await run-and-retry