something I have found vaguely useful that I just uploaded to CPAN for people to play with
Mojo::Promise::Role::Repeat,
adds a
repeat() method to the promise class/objects.
The essential idea is that
$promise->repeat(sub{...})
is equivalent to
$promise->then(sub{...})->then(sub{...})->then(sub{...})->then(sub{...}) # .... forever
except that repeat() also returns a "final" promise, which is
- rejected, if any iteration dies with a value or returns a promise that gets rejected
- resolved with @values, if any iteration calls $_->(@values)
and if any run of the handler sub{...} returns normally or with a promise that gets resolved, those values get fed to the next run,
$_ being bound, at the start of each run, to an escape function that doesn't return -- the moral equivalent of a break statement -- but you can also use this function to break out of nested loops/handlers as well (though you'll need to stash it in a lexical if you're going to do that).
The pattern that seems to be coming up a lot for me is
$ua->get_p($first_url)->repeat(sub {
# ... parse page ...
$_->() if (victory);
# ...
$ua->get_p($next_url);
})
(I may eventually want to petition for some form of this to be added to Mojo::Promise, but one thing at a time...)