【问题标题】:Return error from async function to caller of synchronous function [duplicate]从异步函数向同步函数的调用者返回错误[重复]
【发布时间】:2019-05-12 08:33:57
【问题描述】:

我正在学习 Tokio/futures,但在主函数中找不到将错误返回给调用者的方法;这可能吗?

我的用例是运行时同步的 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,
}

【问题讨论】:

    标签: rust rust-tokio


    【解决方案1】:

    如果您想从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")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      • 2019-02-27
      • 2015-08-15
      • 2023-02-10
      • 2012-07-25
      • 2021-02-23
      • 2019-09-30
      相关资源
      最近更新 更多