Re: [Mojolicious] iterated promises (Mojo::Promise::Role::Repeat)

15 views
Skip to first unread message

Dan Book

unread,
Oct 1, 2019, 10:00:28 AM10/1/19
to mojol...@googlegroups.com
You might look at the existing art of  https://metacpan.org/pod/Future::Utils#REPEATING-A-BLOCK-OF-CODE which can be used with Mojo::Promise via futurify/promisify, and seems a lot clearer to me.

-Dan

On Tue, Oct 1, 2019 at 9:04 AM Roger Crew <cr...@cs.stanford.edu> wrote:
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...)

--
You received this message because you are subscribed to the Google Groups "Mojolicious" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mojolicious...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/mojolicious/8ab45fa4-2b24-417a-8f57-4b99cfe82a4b%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages