Does `await` and `then` behave the same?

Hi, I'm a beginner to std futures. I wonder if there are any differences between

async {
    async_thing().await; 
    async_foo().await;
}

and

async {
    async_thing().then(|| async {async_foo().await});
}

?

The latter will produces future of future as the outer future is wrapped with async{} without .await attached. Beside it both are equal after compilation. But you can .await within branches and loops.

1 Like

Almost the same! The second code block gives this warning:

warning: unused `futures_util::future::future::then::Then` that must be used
  --> src/main.rs:11:5
   |
11 |     async_thing().then(|_| async {async_foo().await});
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: `#[warn(unused_must_use)]` on by default
   = note: futures do nothing unless you `.await` or poll them

The reason for this warning is that you need to await the return value of then. The closure also accepts a single argument, which I've added:

async {
    async_thing().then(|_| async {async_foo().await}).await;
}

Note that this is also the same as your first code block:

async {
    async_thing().then(|_| async_foo()).await;
}

This is also the same:

async {
    async { async_thing().await }.then(|_| async_foo()).await;
}

The argument I ignored in the closure is the return value of the first future. In general async { some_async_fn().await } is the same as some_async_fn().

1 Like