在 Rust 中,如何在闭包内(如在映射内)调用异步方法?

Bru*_*uce 4 closures rust async-await

我有以下内容:

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();
}
Run Code Online (Sandbox Code Playgroud)

显然,我不能在外壳内使用等待。我已经尝试了几种不同的方式来使用 futures::streams 与 iter()、map() 和collect() 以及await,但一直无法通过Vec。有什么建议么?

isa*_*tfa 9

您可以将闭包的主体包装在一个async块中,将您转换ids为 vec of Future<Output = Foo>,然后使用该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();
}
Run Code Online (Sandbox Code Playgroud)

游乐场

编辑:显然,使用该try_join_all功能无需使用异步块。