Return 异步移动块中的任何内容
Return anything in async move block
所以我实施了 代码示例并对其进行了一些更改。现在看起来像这样:
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;
}
一切正常,直到我想要 return 不同于包含文本的 rawJson
-Variable 的东西。我想 return 解析的 json 和相应的 snp-element 到另一个函数,然后从 JSON-Object 过滤一些信息并将其存储在相应的 snp-Object 中。但是每当我更改获得 returned 的对象时,我都会收到以下错误:
error[E0277]: the ?
operator can only be used in an async block that
returns Result
or Option
...
然后它继续将整个 async move
-Block 标记为错误的来源。我将如何处理 return 不同的事情?
编辑:我现在 return Ok((json,snp)) 并得到
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`
如错误所述,如果 async
块的 return 值为 Result
或 Option
,则只能使用 ?
。 rawJson
的类型是 Result<String>
所以当你 return 它时,它工作正常。但是,您现在正在尝试 return 一个元组,所以它会抱怨您不能再使用 ?
了。对此的解决方案是 return Ok((json, snp))
。
所以我实施了
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;
}
一切正常,直到我想要 return 不同于包含文本的 rawJson
-Variable 的东西。我想 return 解析的 json 和相应的 snp-element 到另一个函数,然后从 JSON-Object 过滤一些信息并将其存储在相应的 snp-Object 中。但是每当我更改获得 returned 的对象时,我都会收到以下错误:
error[E0277]: the
?
operator can only be used in an async block that returnsResult
orOption
...
然后它继续将整个 async move
-Block 标记为错误的来源。我将如何处理 return 不同的事情?
编辑:我现在 return Ok((json,snp)) 并得到
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`
如错误所述,如果 async
块的 return 值为 Result
或 Option
,则只能使用 ?
。 rawJson
的类型是 Result<String>
所以当你 return 它时,它工作正常。但是,您现在正在尝试 return 一个元组,所以它会抱怨您不能再使用 ?
了。对此的解决方案是 return Ok((json, snp))
。