Day 14 - Waiting for Alternatives
Yesterday's look at needs_all was our first look into an actual concurrent use-case where we can really benefit from the asynchronous nature of a Future, to combine multiple page requests concurrently and wait for them all to respond.
Today we look at a similar function, needs_any, which also takes a list of individual futures and returns a new future to represent their combination. In this instance, the new future will complete the first time any of its components completes successfully, or will fail once all of its individual components have failed.
my $f = Future->needs_any( GET( "http://uk.my-site-here.com/cache/a" ), GET( "http://de.my-site-here.com/cache/a" ), GET( "http://us.my-site-here.com/cache/a" ), ); my $resp = $f->get;
Here we have started three different HTTP GET operations from three different servers, in the hope that whichever one is closest will respond first, thus making the overall future return the page. If that server happened to return an error, this will be ignored while there are still other alternatives available. The overall future will only yield an error if all the servers do. This gives us an easy way to attempt a variety of strategies to provide an answer to a given question.
But does it stop other fetches when one of them succeeds, or does it require explicit action?
ReplyDeleteA curious question, and one that I'll be answering in a later post.. :)
DeleteBTW, Perl 6 Advent Calendar has an article about Asynchronous Programming: Promises and Channels (Promises == Futures).
ReplyDelete