The following piece of code is taken from the tokio crate tutorial
use tokio::io::{self, AsyncWriteExt};
use tokio::fs::File;
#[tokio::main]
async fn main() -> io::Result<()> {
let mut file = File::create("foo.txt").await?;
// Writes some prefix of the byte string, but not necessarily all of it.
let n = file.write(b"some bytes").await?;
println!("Wrote the first {} bytes of 'some bytes'.", n);
Ok(())
}
Why do we need to .await
when creating a file?
let mut file = File::create("foo.txt").await?;
In other words, why do we need to create a file asynchronously? After all, we can't write to a file if it is not created yet, and hence it's enough simply to block on creating. If it creates successfully then write to it asynchronously, otherwise simply return an error. I definitely miss something.
UPDATE:
Please don't try to long-explain what asynchronous programming is, or what .await
does. I know these topics very well. My question is: what is the reason in this example of creating a file asynchronously?