by shepmaster · 7y ago · 0 comments
let result = executor::block_on({
let one = async { do_something_useful_one() };
let two = async { do_something_useful_two() };
one.await + two.await
});
See examples in:- What is the purpose of async/await in Rust? — https://stackoverflow.com/a/52835926/155423
And why this might be a bad idea in:
- What is the best approach to encapsulate blocking I/O in future-rs? — https://stackoverflow.com/q/41932137/155423
What you need is:
use futures::join;
let result = executor::block_on({
let one = async { do_something_useful_one() };
let two = async { do_something_useful_two() };
let (one, two) = join!(one, two);
one + two
});
I feel like this might be a common stumbling block and hope there will be a Clippy check for this or something.In the spirit of getting it right, your code is missing an `await` and `join` is back to a function in alpha18. Here's the currently working (this time tested!) code:
#![feature(async_await)]
use futures::{executor, future}; // 0.3.0-alpha.18
fn main() {
let result = executor::block_on(async {
let one = async { do_something_useful_one() };
let two = async { do_something_useful_two() };
let (one, two) = future::join(one, two).await;
one + two
});
println!("{}", result);
}
fn do_something_useful_one() -> i32 { 1 }
fn do_something_useful_two() -> i32 { 2 }The sequential but still async version in Kotlin is simply
val result = runBlocking {
doSomethingUsefulOne() + doSomethingUsefulTwo()
}
No awaits necessaryAnd the syntax is surprisingly similar, especially considering we are supposedly comparing a low level language to a high level one.
See the sibling comment [1] where I actually tested and ran the code, finally. ;-). I was unaware that Kotlin would race two `async` blocks, so we had to use the `join` combinator here.