pub fn select<I>(
pending_reqs: I
) -> (Result<Response, SendError>, Vec<PendingRequest>)where
I: IntoIterator<Item = PendingRequest>,
Expand description
Given a collection of PendingRequest
s, block until the result of one of the requests is
ready.
This function accepts any type which can become an iterator that yields requests; a common
choice is Vec<PendingRequest>
.
Returns a tuple (result, remaining)
, where:
-
result
is the result of the request that became ready. -
remaining
is a vector containing all of the requests that did not become ready. The order of the requests in this vector is not guaranteed to match the order of the requests in the argument collection.
Examples
Selecting using the request URI
You can use Response::get_backend_request()
to inspect the request that a response came
from. This example uses the URL to see which of the two requests finished first:
use fastly::{Error, Request};
// Send two asynchronous requests, and store the pending requests in a vector.
let req1 = Request::get("http://www.origin.org/meow")
.send_async("TheOrigin")?;
let req2 = Request::get("http://www.origin.org/woof")
.send_async("TheOrigin")?;
let pending_reqs = vec![req1, req2];
// Wait for one of the requests to finish.
let (resp, _remaining) = fastly::http::request::select(pending_reqs);
// Return an error if the request was not successful.
let resp = resp?;
// Inspect the response metadata to see which backend this response came from.
match resp
.get_backend_request()
.unwrap()
.get_url()
.path()
{
"/meow" => println!("I love cats!"),
"/woof" => println!("I love dogs!"),
_ => panic!("unexpected result"),
}
Selecting using the backend name
You can also use Response::get_backend_name()
to identify which pending request in the given
collection finished. Consider this example, where two requests are sent asynchronously to two
different backends:
use fastly::{Error, Request};
// Send two asynchronous requests, and store the pending requests in a vector.
let req1 = Request::get("http://www.origin-1.org/")
.send_async("origin1")?;
let req2 = Request::get("http://www.origin-2.org/")
.send_async("origin2")?;
let pending_reqs = vec![req1, req2];
// Wait for one of the requests to finish.
let (resp, _remaining) = fastly::http::request::select(pending_reqs);
// Return an error if the request was not successful.
let resp = resp?;
// Inspect the response to see which backend this response came from.
match resp.get_backend_name().unwrap() {
"origin1" => println!("origin 1 responded first!"),
"origin2" => println!("origin 2 responded first!"),
_ => panic!("unexpected result"),
}
Panics
Panics if the argument collection is empty, or contains more than
fastly_shared::MAX_PENDING_REQS
requests.
Panics if the backend response exceeds any of the limits configured by
ResponseLimits
.