Day 17 - Returning a List of Results
We have now seen how Future::Utils::repeat can create control structures to repeatedly run a piece of code returning a future, until some ending condition occurs. When it finishes, the result of the repeat future yields the value of the final attempt it tried.
Sometimes though, we want to run an operation repeatedly and collect up all the results it yielded, rather than just the final one. If we have a list of things to iterate on and perform an operation on each we may wish to gather all the results from this. To do that we can use Future::Utils::fmap.
my $f = fmap { my ( $id ) = @_; GET("http://my-site-here.com/items/$id") } foreach => [ 1 .. 200 ]; my @pages = $f->get;
Similar to the cases of repeat, here the returned future once again represents the overall operation of running the loop, and will only complete once the loop has finished running. Each item in the foreach list is given to each call to the code block inside. However, instead of the future yielding just the last result, all of the results are collected up and returned in a list.
No comments:
Post a Comment