async, await, block_on()
-
async: keyword is syntactic sugar. The compiler replaces the
return type with a future
await
async main(): You cannot make main async, without additional instructions to the compiler You need an executor to run async code
block_on(): blocks the current thread until the provided future has run to completion
use futures::executor::block_on;
async fn count_to(count: i32) {
for i in 0..count {
println!("Count is: {i}!");
}
}
async fn async_main(count: i32) {
count_to(count).await;
}
fn main() {
block_on(async_main(4));
}
$ cargo run
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Future
-
Asynchronous operation is based on "futures", which represent work that
may be completed in the future. Futures are "polled" until they signal
that they are complete
future is trait.
await
-
The .await keyword, applied to a Future, causes the current async
function to pause until that Future is ready, and then evaluates to its
output.
await is used to wait for another async function.
await vs block_on()
| await | block_on() | |
|---|---|---|
| Blocks current thread | no | yes |
| wait for future to complete | yes | yes |
| Other tasks in async function can run? | yes | no |