Home > Net >  Why do we need to await?
Why do we need to await?

Time:10-29

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?

CodePudding user response:

There is no practical reason to use .await in this simplistic example. One could argue this is a bad example, as it does not show any performance improvement over normal synchronous programming. However, a practical example of async is typically more complex, and the purpose of this example is to introduce the basic syntax.

CodePudding user response:

Working with the file system is an asynchronous task. You are requesting to either write or read from the operating system which works independently of your program. your program can do other stuff while the file is loading. Await basically tells your program to stop execution of this function until the data requested is ready.

  • Related