1

给定函数返回每个项目可能失败的流:

pub type Error = Box<dyn error::Error>;
pub type Result<A> = result::Result<A, Error>;
fn query_paginated_items(params: Query) -> impl Stream<Item = Result<Item>> { 
  ... 
}

我想将它的结果展平为像这样的项目向量的结果的未来,

use futures::stream::TryStreamExt;

async fn query_for_all_items(params: Query) -> Result<Vec<Item>> {
  query_paginated_items(params)
    .try_collect::<Vec<Item>>()
    .await
}

我希望将 Stream 展平为 Future 是一项微不足道的任务,但 Rust 的编译器却用另一个神秘的错误让我望而却步。

[rustc] [E] future cannot be sent between threads safely

future created by async block is not `Send`

help: the trait `std::marker::Send` is not implemented for `(dyn std::error::Error + 'static)`
note: required for the cast to the object type `dyn futures::Future<Output = std::result::Result<std::vec::Vec<Item>, std::boxed::Box<(dyn std::error::Error + 'static)>>> + std::marker::Send`

我尝试避免try_collect并在结果出现时循环遍历结果:

  let mut stream = query_paginated_items(params);
  let mut items = Vec::new();
  while let Some(item) = stream.next().await {
    items.push(item?);
  }
  Ok(item)

但它抱怨我的流没有固定。如果我尝试通过以下方式固定我的流:

  let mut stream = Box::pin(query_paginated_items(params));

然后我再次收到“不可发送”错误。

4

0 回答 0