rust - Rust:如何在功能链中使用await

标签 rust async-await

所需代码:
注释掉的块可以编译并工作,但是我想从嵌套的匹配样式转变为更简洁的函数链

async fn ws_req_resp(msg: String, conn: PgConn) -> Result<String, Box<dyn std::error::Error>>{
    let req: WSReq = serde_json::from_str(&msg)?;

    match req.request_type{
        "upsert_competitions" => {
            // let dr = serde_json::from_value(req.data);
            // match dr{
            //     Ok(d) => match upsert_competitions(conn, d).await{
            //         Ok(x) => serde_json::to_string(&x).map_err(|e| e.into()),
            //         Err(e) => Err(Box::new(e))
            //         }
            //     Err(e) => Err(Box::new(e))
            // }
            serde_json::from_value(req.data).and_then(|d| async move {
                upsert_competitions(conn, d).await}).and_then(|r| serde_json::to_string(&r))
                .map_err(|e| e.into())
        },
        uwotm8 => {
            Err(Box::new(InvalidRequestError{req_type: uwotm8.to_string()}))
        }
    }
}
upsert_competitions签名pub async fn upsert_competitions(conn: PgConn, new: Vec<ApiNewCompetition>) -> Result<Vec<DbCompetition>, diesel::result::Error>
错误:
expected enum `std::result::Result<_, serde_json::error::Error>`
           found opaque type `impl core::future::future::Future`

尝试将等待放在多个地方而不编译。
相信等待 future 的人们应该坐在那里直到完成,然后返回结果。

(对我来说,从这个函数返回一个 future 可能更好;然后在外部解开。但是我不明白为什么链中的await失败了,所以很明显我缺乏理解...也试图返回一个 future 我遇到编译器不知道返回大小的问题)

完整的代码
https://github.com/open-fantasy-sports/fantasy-sport-api-rust/blob/ef9db156efa8dbc159eae1c80fb7ac0a6a3ddee3/result_server/src/main.rs#L63

最佳答案

有人告诉我不能在这样的功能链中使用await。

当我切换到返回Box<dyn std::error::Error + Sync + Send + 'static>错误类型时。
然后我就可以再次成功使用?运算符来输入中央代码
(以前认为这是由于错误的错误返回类型而导致失败)。

因此,即使不更改功能,也可以使用此语法来使代码美观和可读。

更新的代码:

pub async fn upsert_competitions(req: WSReq, conn: PgConn, ws_conns: &mut WSConnections_, user_ws_id: Uuid) -> Result<String, BoxError>{
    let deserialized: Vec<NewCompetition> = serde_json::from_value(req.data)?;
    let competitions_out= db::upsert_competitions(&conn, deserialized.into_iter().map(transform_from).collect_vec())?;
    if let Some(ws_user) = ws_conns.lock().await.get_mut(&user_ws_id){
        sub_to_competitions(ws_user, competitions_out.iter().map(|c| &c.competition_id)).await;
    }
    publish_competitions(ws_conns, &competitions_out).await;
    let resp_msg = WSMsgOut::resp(req.message_id, req.method, competitions_out);
    serde_json::to_string(&resp_msg).map_err(|e| e.into())
}

关于rust - Rust:如何在功能链中使用await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61255446/

相关文章:

pointers - 如何强制 Rust 获得非安全方法分配的内存的所有权?

rust - 如何关闭已修改并正在执行的 `futures::sync::mpsc::Receiver` 流?

c# - 在Ui线程上执行同步操作

rust - 如果它的生命周期是静态的,我如何通过引用拥有一个字符串?

rust - 无法返回对临时值的引用

rust - 编译时检查编译器是否nightly

javascript - 使用类/异步等待时获取未定义的 "this"

c# - 处理 C# AggregateException 的正确方法

vue.js - 如何将 Axios 调用循环与等待函数结合起来?

c# - 验证正在等待任务