您如何在封闭空间内调用异步方法,例如 Rust 中的 map?
How do you call an async method within an enclosure, like map in Rust?
我有以下内容:
struct Foo {
id: u32,
}
impl Foo {
async fn get(id: u32) -> Result<Self, Box<dyn Error>> {
Ok(Self{ id })
}
async fn something() {
let ids = vec![1000, 1001];
// conceptually, I'd like to do something like this...
let result: Vec<Foo> = ids.iter().map(|id| Foo::get(id).await.unwrap()).collect();
}
显然,我不能在外壳内使用 await。我尝试了几种不同的方法来使用 futures::streams with iter(), map() and collect() and await,但是没能通过 Vec。有什么建议吗?
你可以将闭包的主体包裹在一个 async
块中,将你的 ids
变成一个 Future<Output = Foo>
的 vec,然后使用 futures::future::join_all
函数来一次等待它们(或者,也许更好,使用 try_join_all
函数来获得结果):
extern crate futures;
use futures::future;
use std::error::Error;
struct Foo {
id: u32,
}
impl Foo {
async fn get(id: u32) -> Result<Self, Box<dyn Error>> {
Ok(Self { id })
}
}
async fn something() {
let ids = vec![1000, 1001];
let result: Vec<Foo> =
future::try_join_all(ids.iter().map(|id| Foo::get(*id)))
.await
.unwrap();
}
编辑: 显然,有了try_join_all
函数就没有必要使用异步块了。
我有以下内容:
struct Foo {
id: u32,
}
impl Foo {
async fn get(id: u32) -> Result<Self, Box<dyn Error>> {
Ok(Self{ id })
}
async fn something() {
let ids = vec![1000, 1001];
// conceptually, I'd like to do something like this...
let result: Vec<Foo> = ids.iter().map(|id| Foo::get(id).await.unwrap()).collect();
}
显然,我不能在外壳内使用 await。我尝试了几种不同的方法来使用 futures::streams with iter(), map() and collect() and await,但是没能通过 Vec。有什么建议吗?
你可以将闭包的主体包裹在一个 async
块中,将你的 ids
变成一个 Future<Output = Foo>
的 vec,然后使用 futures::future::join_all
函数来一次等待它们(或者,也许更好,使用 try_join_all
函数来获得结果):
extern crate futures;
use futures::future;
use std::error::Error;
struct Foo {
id: u32,
}
impl Foo {
async fn get(id: u32) -> Result<Self, Box<dyn Error>> {
Ok(Self { id })
}
}
async fn something() {
let ids = vec![1000, 1001];
let result: Vec<Foo> =
future::try_join_all(ids.iter().map(|id| Foo::get(*id)))
.await
.unwrap();
}
编辑: 显然,有了try_join_all
函数就没有必要使用异步块了。