我正在学习Tokio /期货,在主函数中找不到将错误返回给调用者的方法;这可能吗?
我的用例是运行时是同步的AWS Lambda,并希望从异步部分返回任何错误。
use futures::Future; // 0.1.26
use reqwest::r#async::Client; // 0.9.14
use reqwest::Error; // 0.1.18
use serde::Deserialize;
use tokio;
fn main() {
let call = synchronous_function();
if let Err(e) = call {
println!("{:?}", e);
}
}
fn synchronous_function() -> Result<(), Error> {
let fut = async_function()
.and_then(|res| {
println!("{:?}", res);
Ok(())
})
.map_err(|_| ());
tokio::run(fut);
Ok(())
}
fn async_function() -> impl Future<Item = Json, Error = Error> {
let client = Client::new();
client
.get("https://jsonplaceholder.typicode.com/todos/1")
.send()
.map_err(Into::into)
.and_then(|mut res| res.json().and_then(|j| Ok(j)))
}
#[derive(Debug, Deserialize)]
struct Json {
userId: u16,
id: u16,
title: String,
completed: bool,
}
答案 0 :(得分:0)
如果您要“退还” tokio::run
中的某些内容,则可以使用一个通讯通道,它将您的结果传输回主线程,如下所示:
fn run_sync<T, E, F>(fut: F) -> Result<T, E>
where
T: Debug + Send + 'static,
E: Debug + Send + 'static,
F: Future<Item = T, Error = E> + Send + 'static,
{
let (sender, receiver) = tokio::sync::oneshot::channel();
let exec = fut.then(move |result| {
sender.send(result).expect("Unable to send result");
Ok(())
});
tokio::run(exec);
receiver.wait().expect("Receive error")
}