Does aysnc fn gets called without await?

Say I have:

use tokio::net::TcpListener;
let listener = TcpListener::bind("127.0.0.1:6142"); // line 2
// sleep 100s
listener.await.unwrap(); // line 4

Does the listener start to listen on "127.0.0.1:6142" since line 2 or line 4?
I vaguely remember future does not do any work unless polled. And I assume await is the syntax sugar for polling. So is the correct answer "line 4"?

Yes, nothing happens until line four. You should however be aware that you can't tell without looking at the signature of the function. For example, I might define a function like this:

fn foo(arg: &str) -> impl Future<Output = u32> {
    println!("Before await: {}", arg);
    async {
        println!("After await.");
        10
    }
}

playground with main

This function will first print something, and then create a future that will not run until it is awaited. That said, a function created with the async keyword will implicitly be an -> impl Future function with an async block around the entire body, so those can never do anything until polled.

Therefore, since bind has the signature

pub async fn bind<A: ToSocketAddrs>(addr: A) -> Result<TcpListener>

it cannot do anything until awaited.

2 Likes

That's a really useful detail! Thanks!

On a single thread program this is definitely true, due to there is only one control flow.
What about two threads where the other thread called await on another unrelated future?

Multiple threads do not really have anything to do with this. Futures do nothing until polled.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.