gpt4 book ai didi

rust - 如何解锁 future 的线程并返回结果

转载 作者:行者123 更新时间:2023-11-29 08:28:20 24 4
gpt4 key购买 nike

我决定使用 hyper create 来构建一个读取 POST 方法主体数据的服务器。 How do I synchronously return a value calculated in an asynchronous Future in stable Rust?解释了我正在寻找的部分内容,但我不想使用 tokio::runfuture::lazy因为根据我的理解,hyper 使用 Tokio 和 futures 并且 hyper body 返回一个流。我想要完成的是找到其他处理流的方法并获得更多关于 hyper 的知识 Request方法。

在第一种方法中,我 concat2然后调用wait . wait阻塞当前线程,所以我的代码挂起。

if Method::POST == req.method() {
let body = req.into_body().concat2().wait();
// convert to json and do something with the data.
Ok(Response::new(Body::from("OK: data submitted")))
}

在第二种方法中,我尝试使用 polland_then但我总是得到 NotReady .结果类型为 futures::poll::Async<hyper::Chunk> .

if Method::POST == req.method() {
let body = req.into_body().concat2().poll().and_then(|e| {
// do something
Ok(e)
});

match body {
Ok(e) => println!("{:#?}", e),
Err(r) => println!("{:#?}", r),
};
Ok(Response::new(Body::from("")))
}
  1. 如何解锁当前线程并返回结果?
  2. 如何轮询然后返回结果?

如果可能,请解释如何处理 futures::poll::Async 的良好做法和 wait() .目前,async/await在 Rust 中不稳定,所以我不能使用它。

最佳答案

我相信您已经发现,调用 wait() on futures 是一种反模式 并且完全违背了异步 IO 的目的(因为你阻塞了你的线程 - 以及执行者 - 这样做)。

hyper路由接受实现 IntoFuture 的返回值,为 Option<T> 实现的类型和 Result<T, E>以毯子的方式。因此,您实际编写的内容根本不需要阻塞 - 您只需要像这样组合 future :

if Method::POST == req.method() {
req.into_body().concat2().map(|_body| {
Response::new(Body::from("OK: data submitted"))
})
}

您甚至使用 body您的代码中的内容,但我假设这是出于 MCVE 的目的。 map()里面组合器,该值当前显示为 _body并允许你用它做任何你想做的事。

我猜您是因为文档而发现自己处于这个角落 - 所有组合器都在 FutureExt 上特征对象;它们未在 Future 上定义和 Stream特质本身。因此,在查看 0.2/0.3 文档时,它们不会立即浮出水面,而且看起来您唯一可用的电话似乎是 poll_next()wait()因此。

关于rust - 如何解锁 future 的线程并返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58264529/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com