Run async function from sync context and block

Hi,

I have a program that does not use async, and i've one feature i'd like to use from a library that uses async for everything, so i need to await that functions output in some way. My code is structured like this:

fn main () {
  let handle = lib::Handle::new();
  loop {
    wait_for_some_event();
    handle.do_thing().await; // this is the async function
  }
}

So i want to spawn that function, block until it's finished, and continue with the next iteration afterwards. So, ideally, this works in a way where handle survives the iteration (handle.do_something() takes a non-mutable self-reference).

I'm sorry if this is trivial, but when i try to google it, i just get lots of results for the inverse problem (spawning a blocking task from an async context).

Something like

let mut runtime = tokio::runtime::Runtime::new().unwrap();
let handle = lib::Handle::new();
loop {
    wait_for_some_event();
    runtime.block_on(handle.do_thing());
}

should work. https://docs.rs/tokio/0.2.21/tokio/runtime/struct.Runtime.html

1 Like

thank you, that's what i was looking for! :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.