How to map a vector into actix-web client requests and run them sequentially?

1.1k views Asked by At

I have a vector and I want to make multiple requests and get vector of values. Something like:

use actix_web::client;
let nums = vec![1, 2, 3];
let values = nums.map(|num| {
    client::ClientRequest::get("http://example.com".to_owned() + &num);
});

And I will get [1, 4, 9].

Said another way:

fn question_data(id: &str) -> Box<Future<Item = Question, Error = actix_web::error::Error>> {
    let f = std::fs::read_to_string("auth_token").unwrap();
    let token = f.trim();
    Box::new(
        client::ClientRequest::get("https://example.com/api/questions/".to_owned() + id)
            .header(
                actix_web::http::header::AUTHORIZATION,
                "Bearer ".to_owned() + token,
            )
            .finish()
            .unwrap()
            .send()
            .timeout(Duration::from_secs(30))
            .map_err(actix_web::error::Error::from) // <- convert SendRequestError to an Error
            .and_then(|resp| {
                resp.body().limit(67_108_864).from_err().and_then(|body| {
                    let resp: QuestionResponse = serde_json::from_slice(&body).unwrap();
                    fut_ok(resp.data)
                })
            }),
    )
}

Then I use it:

let question_ids = vec!["q1", "q2", "q3"];

let mut questions = questions_data().wait().expect("Failed to fetch questions");
let question = question_data("q2")
    .wait()
    .expect("Failed to fetch question");
println!("{:?}", question);

let data = question_ids.map(|id| Box::new(question_data(id)));

But I get the error:

245 |     let data = question_ids.map(|id| Box::new(question_data(id)));
    |                             ^^^
    |
    = note: the method `map` exists but the following trait bounds were not satisfied:
            `&mut std::vec::Vec<std::string::String> : futures::Future`
            `&mut std::vec::Vec<std::string::String> : std::iter::Iterator`
            `&mut [std::string::String] : futures::Future`
            `&mut [std::string::String] : std::iter::Iterator`

These are similar but does not compile for me, and also I want to use actix-web:

0

There are 0 answers