我正在学习 Rust 中的并发性,但找不到如何返回和解析Future
.
我怎样才能在 Rust 中实现这个 JavaScript 代码?似乎我必须Future
在某些结构上实现该特征并返回它(对吗?),但我想要一个简单的示例。它setTimeout
可以是任何东西,只要保持简单即可。
function someAsyncTask() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("result")
}, 1_000)
})
}
Run Code Online (Sandbox Code Playgroud)
Rust futures 中与 JavaScriptPromise
构造函数最接近的类比是oneshot 通道,如futures
和中所示tokio
。通道的 \xe2\x80\x9csender\xe2\x80\x9d 与该函数类似resolve
,通道的 \xe2\x80\x9creceiver\xe2\x80\x9d 是一个Future
类似的Promise
函数。没有单独的reject
操作;如果您希望传达错误,可以通过传入Result
通道来实现。
翻译你的代码:
\nuse 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 中执行此操作。两者应该都相当罕见。
您可以创建的最直接的方法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)
归档时间: |
|
查看次数: |
1300 次 |
最近记录: |