I'm learning concurrency in rust and can't find a simple example how to return and resolve a Future
.
How can I implement this javascript code in rust? It seems like I have to implement the Future
trait on some struct and return it (right?), but I want a straightforward example. Instead of setTimeout
it can be anything, just keep it simple.
function someAsyncTask() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("result")
}, 1_000)
})
}
The closest analogue in Rust futures to JavaScript's Promise
constructor is the oneshot channel, as seen in futures
and tokio
. The “sender” of the channel is analogous to the resolve
function, and the “receiver” of the channel is a Future
that works like the Promise
does. There is no separate reject
operation; if you wish to communicate errors, you can do that by passing Result
in the channel.
Translating your code:
use futures::channel::oneshot;
fn some_async_task() -> oneshot::Receiver<&'static str> {
let (sender, receiver) = oneshot::channel();
set_timeout(|| { // not a real Rust function, but if it were...
sender.send("result").unwrap()
}, 1_000);
receiver
}
Note that just like you only need new Promise
in JS if you are translating something callback-like into the promise world, you only need to do this in Rust if you need to cause a future to complete from an outside event. Both should be fairly rare.