0

So I implmented this code-example and changed it up a little. It now looks like this:

pub async fn loadAllSNPData(&mut self, client: &Client) {


let bodies = stream::iter(&self.snps)
    .map(|snp|  {

        let url = format!("https://ncbi.gov/?db=snp&id={}",snp.identifier);

        let client = &client;

        async move {

            let resp = client.get(&url).send().await?;
            let rawJson = resp.text().await;



            // parse json
            let json: Value = serde_json::from_str(&rawJson).expect("JSON was not well-formatted");
            
            Ok((json,snp))
        }

    })
    .buffer_unordered(PARALLEL_REQUESTS);

bodies
    .for_each(|b| {
        async {

            match b {
                Ok(b) => println!("Got {} bytes", b),
                Err(e) => eprintln!("Got an error: {}", e),
            }
        }
    })
    .await;

}

It was all working fine until I wanted to return something different than the rawJson-Variable containing the text. I want to return the parsed json and the according snp-element to another function that then filters some information from the JSON-Object and stored it inside the corresponding snp-Object. But whenever I change the object that gets returned I get the following error:

error[E0277]: the ? operator can only be used in an async block that returns Result or Option...

It then continues to mark the entire async move-Block as the origin of the error. How would I go about this to return different things?

Edit: I now return Ok((json,snp)) and get

error[E0698]: type inside async fn body must be known in this context

Ok((json,snp))
^^ cannot infer type for type parameter `E` declared on
the enum `Result`

1 Answers1

1

As the error states, you can only use ? if the return value of the async block is a Result or Option. The type of rawJson is a Result<String> so when you return it, it works correctly. However, you are trying to return a tuple now, so it complains that you can't use ? anymore. The solution to this would be to return Ok((json, snp)) instead.

hasali19
  • 90
  • 1
  • 5
  • 1
    Makes sense, but there is still something in my way. If I return Ok((json,snp)) I get `error[E0698]: type inside async fn body must be known in this context` and `cannot infer type for type parameter E declared on the enum Result` points to the `Ok` –  Jul 26 '20 at 08:53
  • Hmm, does explicitly specifying the type of the `snp` argument help? – hasali19 Jul 26 '20 at 09:09
  • 2
    Actually, I think the issue is that it can't infer the type of the error in the returned result. You could solve this by returning `Ok((json, snp)) as reqwest::Result<_>`. – hasali19 Jul 26 '20 at 09:25
  • That was nearly it! `Ok((json,snp)) as reqwest::Result<(_,_)>` is a pretty general solution that worked for me. –  Jul 26 '20 at 09:54