How to deal with non-awaited futures?

Hey, Community! I'm wondering what's the best way to deal with non-awaited tasks (i.e. by spawning them). The more I read the documentation the more confused I get on wether there's a proper way to deal with them. My concerns are:

  • If the task is not guaranteed to complete, is there a way to cancel it or time it out?
  • Is it necessary to add yield points to the code so that the runtime can keep polling the task to completion?

Thanks in advance.

Can you perhaps give a bit more context? Spawning a task will make it start running immediately.

Indeed. I was actually thinking that my first message might have insufficient context >.<.

The problem I was trying to address initially was about how to start a future without awaiting for it, so that the current function returns faster. This is an example of such case:

async fn myAsyncHandler(userId: Uuid) -> Result<User, Error> {
  // call some other function, i.e. get User

  let user: User = myDatabase.getUser(userId).await?;

  // do some other expensive thing with the user, but that is not necessary for the current handler to 


I mean, spawning does exactly that: makes it run in the background. In what situation do you want something special to happen?

The thing is that the documentation says that this task is not guaranteed to complete, so I was afraid that the task may just run forever in some cases :S.

In other languages we await for such futures with a timeout, so that they are forcefully terminated if they do not complete during such time span.

I couldn't find in the documentation if this is the case for Rust, hence why I'm asking about the best way to deal with such spawned tasks :).

That part of the documentation refers to the case where the runtime is shut down while the task is running. This will kill all tasks.

1 Like

I see. Thanks a lot for clarifying it, Alice!

As for timeouts, you can wrap any task in tokio::time::timeout. Rust Futures can be cancelled externally, so they don't have to support cancellation themselves.

1 Like

I guess a legitimate question is about a spawned task, especially those whose JoinHandle has been "lost". In that case the task will be polled until the runtime shutdown.

So, when spawning a(n impl) Future, it's good to know that one can wrap it beforehand within a timeout, or keep the returned JoinHandle (which features an .abort() method) to later on stop polling it.

1 Like