代码之家  ›  专栏  ›  技术社区  ›  rofrol

如何将向量映射到actix web客户端请求并按顺序运行它们?

  •  0
  • rofrol  · 技术社区  · 7 年前

    我有一个向量,我想提出多个请求并得到向量值。类似于:

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

    我会得到 [1, 4, 9] .

    另一种说法是:

    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)
                    })
                }),
        )
    }
    

    然后我用它:

    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)));
    

    但我得到了错误:

    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`
    

    0 回复  |  直到 7 年前
    推荐文章