我怎样才能“解决”生锈的未来?

Lev*_*vap 1 concurrency rust

我正在学习 Rust 中的并发性,但找不到如何返回和解析Future.

我怎样才能在 Rust 中实现这个 JavaScript 代码?似乎我必须Future在某些结构上实现该特征并返回它(对吗?),但我想要一个简单的示例。它setTimeout可以是任何东西,只要保持简单即可。

function someAsyncTask() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("result")
    }, 1_000)
  })
}
Run Code Online (Sandbox Code Playgroud)

Kev*_*eid 8

Rust futures 中与 JavaScriptPromise构造函数最接近的类比是oneshot 通道,如futures和中所示tokio。通道的 \xe2\x80\x9csender\xe2\x80\x9d 与该函数类似resolve,通道的 \xe2\x80\x9creceiver\xe2\x80\x9d 是一个Future类似的Promise函数。没有单独的reject操作;如果您希望传达错误,可以通过传入Result通道来实现。

\n

翻译你的代码:

\n
use futures::channel::oneshot;\n\nfn some_async_task() -> oneshot::Receiver<&\'static str> {\n    let (sender, receiver) = oneshot::channel();\n  \n    set_timeout(|| {  // not a real Rust function, but if it were...\n      sender.send("result").unwrap()\n    }, 1_000);\n  \n    receiver\n}\n
Run Code Online (Sandbox Code Playgroud)\n

请注意,就像您只需要new Promise在 JS 中将类似回调的内容转换到 Promise 世界中一样,如果您需要使 future 从外部事件完成,则只需要在 Rust 中执行此操作。两者应该都相当罕见。

\n


caf*_*e25 5

您可以创建的最直接的方法fn() -> impl Future是简单地使用一个async函数:

use std::time::Duration;
use tokio::time;

async fn some_async_task() -> &'static str {
    time::sleep(Duration::from_millis(1_000)).await;
    "result"
}
Run Code Online (Sandbox Code Playgroud)

如果你“删除”一层语法糖,就会变成下面的fn返回一个async块。

use std::time::Duration;
use std::future::Future;

use tokio::time;

fn some_async_task() -> impl Future<Output = &'static str> {
    async {
        time::sleep(Duration::from_millis(1_000)).await;
        "result"
    }
}
Run Code Online (Sandbox Code Playgroud)