Tao Hong
Tao Hong

Reputation: 31

Function A start Function B, how to ensure B continue to execute after A finishes

A async function B is called in the async A function, and then the function C which runs a loop starts in A. How to ensure that C continues to execute after B finishes executing.

async fn A() -> Result<()>{
  // start B
  B().await?;
  Ok(())
}

async fn B() -> Result<()> {
  //start C
  C();
  Ok(())
}

fn C(){
  //running a loop
  loop{
    ...
  }
}

If possible, please attach a rust demo;

Upvotes: 2

Views: 51

Answers (1)

drewtato
drewtato

Reputation: 12747

In standard rust, you would have to return C() without awaiting it, and have A await it, possibly concurrently with other futures. You could also spawn a thread to run C(), but that defeats the purpose of using async.

When you have a runtime, you can spawn it on that. For example, with tokio::task::spawn:

async fn B() -> Result<()> {
  //start C
  tokio::task::spawn(C());
  Ok(())
}

You may still want to return the JoinHandle to A.

If you are writing a library and don't want to depend on a specific runtime, you can take a function that accepts a future:

async fn B<F, R>(f: F) -> Result<R>
where
    F: FnOnce(Pin<Box<dyn Future<Output = ()> + Send + 'static>>) -> R,
{
  let r = f(Box::pin(C()));
  Ok(r)
}

You may need different traits on F or R. I also don't think it is possible to do this without Box, unless you have access to type alias impl trait, or make a concrete Future type instead of using an async function.

Here is a playground of this working.

Upvotes: 1

Related Questions