Need help in understanding what really .await is

I was exploring async/.await and this book explains .await as

Unlike block_on , .await doesn't block the current thread, but instead asynchronously waits for the future to complete, allowing other tasks to run if the future is currently unable to make progress

So to experiement this I wrote below piece of code where I .await multiple futures concurrently using join!() but the o/p of this code confuses my understanding of .await from the book.

#[tokio::main]
async fn main() {
   let foo = read_from_console();
   let bar = fun();
// .awaiting  multiple futures concurrently using join!()
   join!(foo,bar);
}

async fn read_from_console() {
   let mut line = String::new();
   println!("Enter your name :");
   std::io::stdin().read_line(&mut line).unwrap();
   println!("Hello , {}", line);
}

async fn fun() {
    println!("hello from fun");
}

--------------------------------
o/p :
Enter your name :
foo
Hello , foo

hello from fun
---------------------------------

If I go by the book then bar should be allowed to run when foo is still waiting(blocked) for the user input.But here bar is run only after foo is ran into completion. why is it so?

You're not awaiting anything here (except implicitly in join), so I'm not sure what this code is supposed to check.

thanks for pointing out. i have used join!() which is similar to .await but can wait for multiple futures concurrently . i just edited the question.

Neither of your functions does anything asynchronous (I/O in the standard library is synchronous), so async-await basically doesn't do anything in your code.

1 Like

Do not perform long blocking operations within an async function.

1 Like

If you switch std::io with tokio::io, you will need .await.

This is because the Tokio version will detect when it would take a long time, and then "task switch" away. The .await keyword indicates that this is expected, and inserts glue code to transform some types which can handle this behavior (e.g. Future).

Playground link

Start with that code, take out the .await keyword, and see what happens.

1 Like